Tan*_*gar 2 c++ visual-c++ c++11 c++14
#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;
}
Run Code Online (Sandbox Code Playgroud)
此代码的输出是:
CTOR CALLED
CTOR CALLED
分配操作员称为
COPY CTOR CALLED
当我在visual studio中使用手表时,它表明即使在调用重载赋值运算符之前,xin 的值a也已更改.
那么为什么复制构造函数甚至在这里被调用?
因为您从赋值运算符返回值.它应该返回一个引用:
A& operator = (A &d) { ... }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
111 次 |
| 最近记录: |