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