我有一个显示奇怪行为的程序
#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 的第三次调用,此输出很奇怪;
为什么当我没有制作新对象但正在使用旧对象时,会调用额外的复制构造函数打印。
是不是因为中间有临时物体,如果是的话,我可以在这里阻止它们....