![]() |
#2
Jonny02012018-07-14 20:13
|

/**
没有const。
char *name;
**/
#include <iostream>
#include <cstring>
using namespace std;
class Student
{
public:
Student(int n,char *na,float s):no(n),score(s)
{
name=new char[strlen(na)+1];
strcpy(name,na);
}
Student(const Student& s):no(s.no),score(s.score)
{
name = new char[strlen(s.name)+1];
strcpy(name,s.name);
}
~Student()
{
if(name!=NULL)
delete []name;
}
void display()const
{
cout << no << " " << name << " " << score <<endl;
}
protected:
private:
const int no;
char *name;
const float score;
};
int main()
{
const Student stu1(1,"wangming",99);
stu1.display();
const Student stu2(stu1);
stu2.display();
return 0;
}

/**
包含const。
const char * name;
**/
#include <iostream>
#include <cstring>
using namespace std;
class Student
{
public:
Student(int n,char *na,float s):no(n),score(s)
{
name=new char[strlen(na)+1];
strcpy(name,na);
}
Student(const Student& s):no(s.no),score(s.score)
{
name = new char[strlen(s.name)+1];
strcpy(name,s.name);
}
~Student()
{
if(name!=NULL)
delete []name;
}
void display()const
{
cout << no << " " << name << " " << score <<endl;
}
protected:
private:
const int no;
const char *name;
const float score;
};
int main()
{
const Student stu1(1,"wangming",99);
stu1.display();
const Student stu2(stu1);
stu2.display();
return 0;
}