0
如果我有一个需要深度拷贝类的重载赋值操作符,我该如何去做呢? Person类包含一个名称类C++带有赋值运算符的类的深拷贝
Person& Person::operator=(Person& per){
if (this==&per){return *this;}
// my attempt at making a deep-copy but it crashes
this->name = *new Name(per.name);
}
在名称类拷贝构造函数和赋值操作符
Name::Name(Name& name){
if(name.firstName){
firstName = new char [strlen(name.firstName)+1];
strcpy(firstName,name.firstName);
}
Name& Name::operator=(Name& newName){
if(this==&newName){return *this;}
if(newName.firstName){
firstName = new char [strlen(newName.firstName)+1];
strcpy(firstName,newName.firstName);
return *this;
}
首先,赋值和拷贝构造函数采用'const X&'而不仅仅是'X&'。其次,“name”的类型是什么? '姓名&?如果是,它将不起作用。如果不是,请不要使用'new'因为你有泄漏。 – Johan
Uee复制和交换成语:http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom – Davidbrcz