Operator Overloading Enable C++’s operators to work with class object >, +, -, *, / This operators perform differently depending on their context in integer, floating These operators are overloaded C++ allow programmer to overload most operators
Can we make Complex class easier to use as follow? int main() { Complex x,y,z; cout<<“Type in two complex numbers\n”; cin>>x >>y; z = x + y; cout<< x <<“+” <<y<<“=“ <<z<<endl; } Type in two complex numbers (2,3) (3,4) (2,3) + (3,4) = (5,7)
Yes, Overload the operators Operator are overloaded by writing a function definition( header and body) Function name become the keyword operator followed by the symbol for the operator being overloaded operator+ would be used to overload the addition operator(+) Precedence and associativity of an operator cannot be changed by overloading
Where to define overloading operator As non member function Must be friend of the class So it is in class definition class Complex { friend ostream& operator<< (ostream&, const Complex &);... } Function name Return type parameters
Implementation ostream & operator<<(ostream & out, const Complex &c) { out<<“(“<<c.real<<“,”<<c.img<<“)”; return out; // enables cout<<x<<y; }
Overload operator >> In class definition class Complex { friend ostream& operator<< (ostream &, const Complex &); friend istream& operator>> (istream&, Complex &);... }
implementation istream & operator>>( istream & input,Complex & c) { input.ignore(); input>>c.real; input.ignore(); input>>c.img; input.ignore(); return input; }
Operator Overloading 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; }