60 likes | 193 Views
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)
E N D
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 >>, <<)
Arithmetic operators • +, - , *, /, +=, -=, *=, /= • In header class Complex {friend ostream& operator<< (ostream &, const Complex &); friend istream& operator>> (istream&, Complex &); Complex operator+(const Complex &c,)const; ... }
implementation Complex Complex::operator+( Complex &c) { Complex sum; sum.real = real + c.real; sum.img = img+ c.img; return sum; }
In header Complex operator-(const Complex& c); • Implementation Complex Complex::operator-(const complex &c) { return Complex(real-c.real, img=c.img); }
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; }
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