C++ C++;具有赋值运算符的类的深度副本
如果我有一个重载的赋值操作符,需要深度复制一个类,我该怎么做呢? 类Person包含一个名称类C++ C++;具有赋值运算符的类的深度副本,c++,C++,如果我有一个重载的赋值操作符,需要深度复制一个类,我该怎么做呢? 类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::N
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;
}
我将利用现有的复制构造函数、析构函数和添加的
swap()
函数:
Name& Name::operator= (Name other) {
this->swap(other);
return *this;
}
我正在执行的所有复制任务都与此实现类似。缺少的swap()
函数也很容易编写:
void Name::swap(Name& other) {
std::swap(this->firstName, other.firstName);
}
同样地,对于
Person
而言,首先分配并复制构造函数,而不仅仅是X&
。第二,名称的类型是什么<代码>名称&?如果是的话,它就不起作用了。如果没有,请不要使用new
,因为您有泄漏。Uee复制和交换习惯用法: