Thinking about the C + + overloaded operator
#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;}
Execution Result:
Analysis: Execute m3 = m1 + m2 point in time, because the M3 space has been created, so
immediatelyReleased the object created in operator+, printed 1 out, and finally released the remaining 3 objects. If the code is changed to: imaginary M3 = m1 + m2; Because M3 has not been created yet, the objects created in operator+ are not released.
Thinking about the C + + overloaded operator