C + +: Friend operator overloaded function

Source: Internet
Author: User

Operator overloading functions: implements arithmetic operations between objects, (in effect, between attributes of an object), including + (plus sign),-(minus sign), *,/, =, + + 、--、-(minus sign), + (plus)

Operator overloading functions are divided into: friend operator overloaded function, member operator overloaded function

Operator operators overload functions by operation type: Binocular operator overload function, such as add, subtract, multiply, divide, assign; single-mesh operator overload function: Self-add, decrement, sign

Remember: the member operator. and->,sezeof, etc. cannot be overloaded. At least one of the arguments of an operator overloaded function is a class type or reference type.

The following is an example of a friend operator overloaded function:

1#include <iostream>2 using namespacestd;3 classComplex4 {5  Public:6Complex (DoubleR=0.0,DoubleI=0.0);7     voidprint ();8Friend Complexoperator+ (Complex &a,complex &b);9Friend Complexoperator-(Complex &a,complex &b);Ten Private: One     DoubleReal; A     Doubleimag; - }; -Complex::complex (DoubleRDoublei) the { -Real =R; -Imag =i; - } +Complexoperator+ (Complex &a,complex &b) - { + Complex temp; ATemp.real = A.real +b.real; atTemp.imag = A.imag +B.imag; -     returntemp; - } -Complexoperator-(Complex &a,complex &b) - { - Complex temp; inTemp.real = A.real-b.real; -Temp.imag = A.imag-B.imag; to     returntemp; + } - voidComplex::p rint () the { *cout<<Real; $     if(imag>0) cout<<"+";Panax Notoginseng     if(imag!=0) cout<<imag<<'I'<<Endl; - } the intMainintAGRsConst Char*agrv[]) + { AComplex A1 (2.3,4.6), A2 (3.6,2.8), a3,a4; theA3 = A1 + A2;//A3 = operator+ (A1,A2); +A4 = A1-A2;//A4 = operator-(A1-A2); - a1.print (); $ a2.print (); $ a3.print (); - a4.print (); -      the     return 0; -}

Operation Result:

2.3+4. 6i3.6+2. 8i5.9+7. 4i- 1.3+10

C + +: Friend operator overloaded function

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.