c/c++ 重载运算符的思考

时间:2022-10-31 19:51:21

c/c++ 重载运算符的思考

#include <iostream>
using namespace std; class Imaginary{ public:
Imaginary():real(0), imag(0){
cout << "c:" << this << endl;
}
Imaginary(int real, int imag):real(real), imag(imag){
cout << "c:" << this << endl;
}
Imaginary operator+ (const Imaginary &m){
return Imaginary (real + m.real, imag + m.imag);
}
~Imaginary(){
cout << this << endl;
}
private:
int real;
int imag;
}; int main(){
Imaginary m1(10, 20);
Imaginary m2(1, 2);
Imaginary m3;
printf("m3 : %p\n",&m3);
m3 = m1 + m2;
cout << 1 << endl; return 0;
}

执行结果:

c/c++ 重载运算符的思考

分析:执行m3 = m1 + m2的时点,因为m3的空间已经创建过了,所以立即释放了operator+中创建的对象,打印了1出来,最后才释放了其余3个对象。

如果代码改成:Imaginary m3 = m1 + m2; 因为m3还没有被创建过,所以不释放operator+中创建的对象。