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