class complex
{
public:
double real, imag;
complex() { cout << "默认构造函数" << "\n"; }
complex(double r,double i):real(r),imag(i){ cout << "转换构造函数" << "\n"; }
complex(complex&c)
{
real = c.real;
imag = c.imag;
cout << "复制构造函数" << "\n";
}
complex operator = (const complex&c);
};
complex complex::operator=(const complex&c)
{
real = c.real;
imag = c.imag;
cout << "重载=" << "\n";
return *this;
}
上面代码定义了一个复数类,重载了=,并且operator=函数的返回值是complex类。如果执行下面代码:
int main()
{
complex s1(1, 2), s2(2,3),s3;
(s3 = s2) = s1;
cout << "(" << s3.real << "," << s3.imag << ")";
system("pause");
return 0;
}
输出将是
非但没有完成值传递,还多次调用复制构造函数,造成运算速度下降。想知道为什么是这样的输出,需要仔细分析对象的生成过程,明确哪些地方会生成对象。