Thinking about the C + + overloaded operator

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.