[英]why copy constructor & assignment operator both are called in this case
Can anybody explain me, why in my below code, where ms3 = ms1 is done, both copy and assignment operator get called in this line. 谁能解释我,为什么在我的以下代码中,完成了ms3 = ms1的操作,在此行中同时调用了复制和赋值运算符。 In the above mentioned line only overloaded assignment operator should get called as per my knowledge.
在上面提到的行中,据我所知,仅应调用重载的赋值运算符。 But both the copy constructor and assignment operator are getting called.
但是复制构造函数和赋值运算符都被调用。 Please explain me.. why this happens?
请解释一下..为什么会这样?
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;
}
The assignment operator takes its argument by value; 赋值运算符按值接受参数; the copy constructor is used to set up that argument.
复制构造函数用于设置该参数。
To avoid this, your need to rewrite your assignment operator so that it takes a reference, like the copy constructor does. 为避免这种情况,您需要重写赋值运算符,以使其像复制构造函数一样接受引用。 Also you should use
const
: 另外,您应该使用
const
:
MyString(MyString const &str);
MyString & operator=(MyString const &str);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.