2016-11-23 99 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;' –

相关问题