我想改善我對複製構造函數和複製分配的理解。運營商 這裏是我想出了可以將此作業和複製cnstr更好地組織
class Bar
{
char* name;
int zip;
std::string address;
public:
Bar(const Bar& that)
{
//Copy constructor
size_t len = strlen(that.name + 1);
name = new char[len];
strcpy(name, that.name);
//Copy the zip
this->zip = that.zip;
//Copy the address
this->address = that.address;
}
Bar& operator=(const Bar& that)
{
//Assignment operator
if(this != &that)
{
//Copy the name
size_t len = strlen(that.name + 1);
name = new char[len];
strcpy(name, that.name);
//Copy the zip
this->zip = that.zip;
//Copy the address
this->address = that.address;
}
return *this;
}
};
一個簡單的類我的問題是因爲在拷貝構造函數的代碼,拷貝賦值操作符是相同的它更有意義的統一是陷入了深深的複製方法,以便那incase我添加另一個成員變量我不必添加另一行到複製cnstr和複製分配。部分 ?有什麼建議麼 ?
爲什麼你不使用'std :: String? –
@EdHeal:他是,再次檢查:P –
我正在使用兩者。以防萬一我遇到'char *'我也決定使用它。 – Rajeshwar