Topic One: the addition of two complex numbers is accomplished without operator overloading. Generate complex object c1,c2, get c3=c1+c2, and print output C3.
#include <iostream>using namespacestd;classcomplex{ Public: Complex () {real=0; imag=0;} Complex (DoubleRDoublei): Real (R), Imag (i) {} complex Complex_add (complex&C2); voiddisplay (); Private: DoubleReal,imag;}; Complex Complex::complex_add (Complex&C2) {complex C; C.real=real+c2.real;//who calls is who's thisc.imag=imag+C2.imag; returnC;}voidComplex::d isplay () {cout<<"("<<real<<","<<imag<<")"<<Endl;}intMain () {Complex C1 (3.5,4.5), C2 (3.6,4.4), C3; C3=C1.complex_add (C2); C3.display (); return 0;}View Code
Operator Overloading:
function type operator operator name (formal parameter list);
The name of the operator+ operator, which can be interpreted as a function name
Complex complex::operator+ (complex &c2)
{ return complex (REAL+C2.REAL,IMAG+C2.IMAG); }
#include <iostream>using namespacestd;classcomplex{ Public: Complex () {real=0; imag=0;} Complex (DoubleRDoublei): Real (R), Imag (i) {} complexoperator+ (Complex &C2); voiddisplay (); Private: DoubleReal,imag;}; Complex complex::operator+ (Complex & C2)//operator Overloading{ returnComplex (real+c2.real,imag+c2.imag);}voidComplex::d Isplay ()//Output{cout<<"("<<real<<","<<imag<<")"<<Endl;}intMain () {Complex C2 (3.6,4.4), C3; C3=complex (3.5,4.5)+C2; C3.display (); return 0;}View Code
Operator Overloading Example