Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/145.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;具有赋值运算符的类的深度副本_C++ - Fatal编程技术网

C++ C++;具有赋值运算符的类的深度副本

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& 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复制和交换习惯用法: