拷贝构造函数用一个已有同类对象的数据对正在建立的对象进行数据初始化
C++为类提供默认版本的拷贝构造函数
默认复制构造函数可以完成对象的数据成员值简单的复制
对象的数据资源是由指针指示的堆时,默认复制构造函数仅作指针值复制,即为浅拷贝
class TeacherT
{
public:
TeacherT(int id,char* name) {
mid = id;
mname = new char[strlen(name) + 1];//申请内存
strcpy_s(mname, strlen(name) + 1, name);//拷贝
}
//显示的提供一个拷贝构造函数,来完成深拷贝动作
TeacherT(const TeacherT &T) {
if (mname != NULL)
{
delete[] mname;
}
mname = new char[strlen(T.mname) + 1];
strcpy_s(mname, strlen(T.mname) + 1, T.mname);
mid = T.mid;
}
//重载赋值操作符,完成深拷贝动作
TeacherT& operator= (TeacherT &another)
{
if (mname != NULL)
{
delete[] mname;
}
mname = new char[strlen(another.mname) + 1];
strcpy_s(mname, strlen(another.mname) + 1, another.mname);
mid = another.mid;
return *this;
}
~TeacherT() {
cout << "~TeacherT" << endl;
if (mname != NULL)
{
delete[]mname;
}
}
void printT()
{
cout << "mid: " << mid << ends << "mname: " << mname << endl;
}
private:
int mid;
char *mname;
};
使用默认提供的拷贝构造函数(进行浅拷贝)和赋值运算符---出现问题:
显示提供拷贝构造函数(深拷贝)和重载赋值运算符---解决问题: