创建类的时候,对于有指针的成员变量,一定要添加拷贝构造函数和等号(=)重载符。否则进行的是指针指向复制,也就是浅拷贝,类销毁时会重复销毁,造成软件crash。
1. 创建teacher类
2. 添加拷贝构造函数(深拷贝)
3. 添加等号(=)重载符
class Teacher{
public:
Teacher(char* name,int age){
int len = strlen(name) + 1;
this->name = new char[len]; //在堆分配内存
strcpy(this->name,name);
this->age = age;
}
//拷贝构造
Teacher(const Teacher& t){
int len = strlen(t.name) + 1;
this->name = new char[len];
strcpy(this->name, t.name);
this->age = t.age;
}
//重载=
Teacher& operator=(Teacher& t){
int len = strlen(t.name) + 1;
if (this->name != NULL){
delete[] this->name;
}
this->name = new char[len];
strcpy(this->name, t.name);
this->age = t.age;
return *this;
}
~Teacher(){
if (this->name != NULL){
delete[] this->name;
}
this->age = 0;
}
char* name;
int age;
};