Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— 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 FileHeader File Implementation file Driver fileImplementation fileDriver file


Download ppt "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."

Similar presentations


Ads by Google