![](/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.