我有一个程序表现出奇怪的行为
#include <cstdlib>
#include <iostream>
using namespace std;
class man{
int i ;
public:
man(){
i=23;
cout << "\n defaul constructir called\t"<< i<<"\n";
}
man (const man & X) {
i = 24;
cout << "\n COPY constructir called\t"<< i<<"\n";
}
man & operator = (man x ) {
i = 25;
cout << "\n = operator called\t"<< i<<"\n";
return *this;
}
};
int main(int argc, char *argv[])
{
man x;
cout <<"\n ----------\n";
man y = x;
cout <<"\n ----------\n";
x=y;
return 0;
}
显示在
中的输出 defaul constructir called 23
----------
COPY constructir called 24
----------
COPY constructir called 24
= operator called 25
对于 x=y 的第三次调用,这个输出很奇怪;
为什么当我没有创建新对象但正在使用旧对象时调用了复制构造函数的额外打印。
是不是因为中间有临时对象,如果是的话,我能不能把它们停在这里....
最佳答案
因为您的赋值运算符按值获取其参数。您可以改为通过 const 引用来获取它。
关于c++ - 复制构造函数调用 extra,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16865239/