如果我有一个重载的赋值操作符需要深入复制一个类,我将如何去做呢?类Person包含一个名称类。
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;
}发布于 2013-12-07 21:42:11
我将利用现有的复制构造函数、析构函数和添加的swap()函数:
Name& Name::operator= (Name other) {
this->swap(other);
return *this;
}我正在实现的所有复制任务都类似于这个实现。缺少的swap()函数编写起来也很简单:
void Name::swap(Name& other) {
std::swap(this->firstName, other.firstName);
}Person也是如此。
https://stackoverflow.com/questions/20446784
复制相似问题