1 / 6

Operator Overloading (2)

Operator Overloading (2). Operator function can be implemented as class member function Then the left most (or only) operand must be an class object( or a reference to a class object)

Télécharger la présentation

Operator Overloading (2)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Operator Overloading (2) • Operator function can be implemented as class member function • Then the left most (or only) operand must be an class object( or a reference to a class object) • If the left operand must be a object of a different class or build-in type, this operator function must be implemented as a non-member function( as we did for >>, <<)

  2. Arithmetic operators • +, - , *, /, +=, -=, *=, /= • In header class Complex {friend ostream& operator<< (ostream &, const Complex &); friend istream& operator>> (istream&, Complex &); Complex operator+(const Complex &c,)const; ... }

  3. implementation Complex Complex::operator+( Complex &c) { Complex sum; sum.real = real + c.real; sum.img = img+ c.img; return sum; }

  4. In header Complex operator-(const Complex& c); • Implementation Complex Complex::operator-(const complex &c) { return Complex(real-c.real, img=c.img); }

  5. In header Complex operator*(const Complex& c); • Implementation Complex Complex::operator*(const Complex &c) { Complex mul; mul.real = real*c.real-img*c.img; mul.img = real*c.img + img+c.img; return mul; }

  6. In header Complex operator/(const Complex& c); • Implementation Complex Complex::operator*(const Complex &c) { Complex div; double dem; dem = c.real*c.real + c.img+c.img; div.real = (real*c.real+img*c.img)/dem; div.img = (img+c.img -real*c.img )/dem; return div; } Completed Complex class: Header FileImplementation fileDriver file

More Related