Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 10. Operator Functions: Another ... > Case Study: Rational Numbers - Pg. 388

Operator Functions: Another Good idea Complex::Complex(double r, double i) { real =r; imag = i; } // general constructor 388 Complex Complex::operator+(const Complex &b) const { return Complex (real + b.real, imag + b.imag); } void Complex::operator += (const Complex &b) // target changes { real = real + b.real; // add to real component of the target imag = imag + b.imag; } // add to imag component of the target void Complex::operator += (double b) { real += b; } // target object changes // add to real component of the target void Complex::operator + () const // no change to target { cout << "(" << real << ", " << imag << ")" << endl; } int main() { Complex x(20,40), y(30,50), z1(0,0), z2(0,0); cout << " Value of x: "; +x; // cout << " Value of y: "; y.operator+(); // z1 = x.operator+(y); // cout << " z1 = x + y: "; +z1; z2 = x + y; // cout << " z2 = x + y: "; +z2; z1 += x; // cout << " Add x to z1: "; +z1; z2 += 30.0; // cout << " Add 30 to z2: "; +z2; return 0; } // defined, initialized same as x.operator+(); anything goes use in the function call same as z2=x.operator+(y); same as z1.operator+=(x); same as z2.operator+=(30.0); Use the const keyword for parameters of overloaded operator functions that do not change Tip