#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
已被更改。
那么为什么在这里调用拷贝构造函数呢?
只是注意的参数应该是const的参考'A&运算符=(常量&d){...}'同样的拷贝构造函数。 –
并且您想要以其他方式复制'x'的值。即'x = d.x;' –