我想改善我对复制构造函数和复制分配的理解。运营商 这里是我想出了可以将此作业和复制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