One, operator overloading is a member function
#include <iostream>using namespace Std;class Complex {public: double real; Double imag; Complex (Double r = 0.0,double i = 0.0); Complex operator+ (const complex&); Complex operator-(const complex&); void Printcomplex ();}; Complex::complex (Double R, double i) { real = R; Imag = i;} Complex complex::operator+ (const complex& c) { return Complex (REAL+C.REAL,IMAG+C.IMAG);} Complex complex::operator-(const complex& c) { return Complex (REAL-C.REAL,IMAG-C.IMAG);} void Complex::p Rintcomplex () { cout<<real<< "+" <<imag<< "I" <<ENDL;} int main (int argc, const char * argv[]) { Complex A (3,4), B (5,9), c,d; c = a + B; d = b-a; C.printcomplex (); D.printcomplex (); return 0;}
Second, operator overloading becomes a common function
#include <iostream>using namespace Std;class Complex {public: double real; Double imag; Complex (Double r = 0.0,double i = 0.0); void Printcomplex ();}; Complex::complex (Double R, double i) { real = R; Imag = i;} Complex operator+ (const complex& C1, const complex& c2) { return Complex (C1.REAL+C2.REAL,C1.IMAG+C2.IMAG);} Complex operator-(const complex& C1, const complex& c2) { return Complex (C1.REAL-C2.REAL,C1.IMAG-C2.IMAG);} void Complex::p Rintcomplex () { cout<<real<< "+" <<imag<< "I" <<ENDL;} int main (int argc, const char * argv[]) { Complex A (3,4), B (5,9), c,d; c = a + B; d = b-a; C.printcomplex (); D.printcomplex (); return 0;}
Note: the Printcomplex () function does not handle the details of the output.
C + + operator overloading (i)--add and subtract