2016-11-23 90 views
2
#include <iostream> 
using namespace std; 
class A 
{ 
    int x; 
public: 

    A(int a) 
    { 
     x = a; 
     cout << "CTOR CALLED"; 
    } 
    A(A &t) 
    { 
     cout << "COPY CTOR CALLED"; 
    } 
    void display() 
    { 
     cout << "Random stuff"; 
    } 
    A operator = (A &d) 
    { 
     d.x = x; 
     cout << "Assignment operator called"; 
     return *this; 
    } 
}; 

int main() 
{ 
    A a(3), b(4); 
    a = b; 
    return 0; 
} 

這段代碼的輸出是:爲什麼在這裏調用拷貝構造函數?

CTOR CALLED
CTOR CALLED
賦值運算符稱爲
COPY CTOR CALLED

當我使用Visual Studio中的手錶這表明甚至在調用重載賦值操作符之前,x的值a已被更改。

那麼爲什麼在這裏調用拷貝構造函數呢?

回答

3

正如@SomeProgrammerDude已經說了,那是因爲你的價值回報,而不是參考就像你通常與賦值操作符做。我想補充一點,你的任務運營商當前是圍繞着錯誤的方法:

A operator = (A &d) 
{ 
    d.x = x; 
    cout << "Assignment operator called"; 
    return *this; 
} 

通常你通過const引用傳遞d因爲我們要改變的this成員。您正在更改d的成員。這將在功能上將您的a = b;變爲b = a;,因爲a = b;實際上正在改變b的成員!

製作d a const&可以防止這些錯誤。

您應將其更改爲:

A& operator = (A const &d) 
{ 
    x = d.x; 
    cout << "Assignment operator called"; 
    return *this; 
} 
6

因爲您從賦值運算符中按值返回。它應該返回一個參考

A& operator = (A &d) { ... } 
+6

只是注意的參數應該是const的參考'A&運算符=(常量&d){...}'同樣的拷貝構造函數。 –

+3

並且您想要以其他方式複製'x'的值。即'x = d.x;' –

相關問題