Use a friend function in Operator Overloading

Source: Internet
Author: User

In Operator overloading, you can use a friend function to perform the four arithmetic operations of the plural number.

# Include
 
  
Using namespace std; class Complex {public: Complex () // defines the default constructor initialization plural {real = 0; imag = 0 ;} // use the initialization table to initialize the Complex (double r, double I): real (r), imag (I) {} friend Complex operator + (Complex & c1, complex & c2); // Add the plural number to friend Complex operator-(Complex & c1, Complex & c2); // subtract the plural number from friend Complex operator * (Complex & c1, complex & c2); // multiplication of the plural number: friend Complex operator/(Complex & c1, Complex & c2); // division of the plural number void display (); // display the plural private: double real; // real part of the Complex number double imag; // virtual part of the Complex number}; // addition of the Complex number Complex operator + (Complex & c1, Complex & c2) {Complex c3; c3.real = c1.real + c2.real; c3.imag = c1.real + c2.imag; return c3;} // subtraction of Complex numbers Complex operator-(Complex & c1, Complex & c2) {Complex c3; c3.real = c1.real-c2.real; c3.imag = c2.imag-c2.imag; return c3 ;}// multiplication Complex operator * (Complex & c1, Complex & c2) {Complex c3; c3.real = c1.real * c2.real-c1.imag * c2.imag; c3.imag = c2.real * c2.imag + c2.imag * c2.real; return c3;} // division of Complex operators/(Complex & c1, complex & c2) {Complex c3; c3.real = (c1.real * c2.real + c1.imag * c2.imag)/(c2.real * c2.real + c2.imag * c2.imag ); c3.imag = (c1.imag * c2.real-c1.real * c2.imag)/(c2.real * c2.real + c2.imag * c2.imag); return c3 ;}// display the plural void Complex: display () {cout <
  <<'+'<<<'i'<
   


Execution result:


<<'+'<<<'i'<

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.