![](/img/trans.png)
[英]Why is the assignment operator not called in this case in favor of the copy constructor?
[英]why copy constructor & assignment operator both are called in this case
谁能解释我,为什么在我的以下代码中,完成了ms3 = ms1的操作,在此行中同时调用了复制和赋值运算符。 在上面提到的行中,据我所知,仅应调用重载的赋值运算符。 但是复制构造函数和赋值运算符都被调用。 请解释一下..为什么会这样?
class MyString {
private:
char* string;
public:
MyString(char *ptr = NULL);
MyString(MyString &str);
MyString & operator =(MyString str);
~MyString();
};
MyString::MyString(MyString &str) {
printf("Copy Constructor called !!!\n");
int len = strlen(str.string);
string = new char[len+1];
strcpy_s(string, len+1, str.string);
}
MyString::MyString(char* str) {
printf("Constructor called !!!\n");
if (str != NULL) {
int len = strlen(str);
string = new char[len + 1];
strcpy_s(string, len + 1, str);
}
else {
string = NULL;
}
}
MyString & MyString::operator=(MyString str) {
printf("Assignment Operator!!!\n");
if (&str == this) {
return *this;
}
delete[] string;
if (&str != NULL) {
int len = strlen(str.string);
string = new char[len + 1];
strcpy_s(string, len+1, str.string);
}
return *this;
}
MyString::~MyString() {
printf("Destructor\n");
delete[] string;
}
int _tmain(int argc, _TCHAR* argv[])
{
MyString ms = "ABC";
MyString ms1("EFG");
MyString ms2 = ms1;
MyString ms3;
ms3 = ms1;
MyString ms4 = ms3 = ms1;
return 0;
}
赋值运算符按值接受参数; 复制构造函数用于设置该参数。
为避免这种情况,您需要重写赋值运算符,以使其像复制构造函数一样接受引用。 另外,您应该使用const
:
MyString(MyString const &str);
MyString & operator=(MyString const &str);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.