operator overloading
Why?
cout << obj1 << obj2 just like we do cout << i << j; It is easier than obj1.print();
complex1 + complex2 binary operator... the alternative is complex1.add(complex2);
complex1 == complex2 operator... the alternative is complex.equal(complex2);
++date, date++ pre and post unary operator
How to do this?
global function
friend ostream & operator<<( ostream &, const Complex & );
friend Complex operator+ ( const Complex &, const Complex & );
member function
Complex operator-( const Complex & );
Most operators can be implemented with either global or member function, as we do global for + and member for -.
Note that operator << and >> can only be implemented as global friend function. Why?
Binary operator + example
date1+date2 return temporary date object
use i+j as example, cout << i+j
look into code to see temp is allocated and returned in + operator overloading code
return this for cascading
difference between ++date and date++
can we do (i++)++ ? why not?
can we do ++(++i) ? why?
Examples:
Complex number class (.cpp .h and main are attached below)
A few notes:
By looking at the test code, can we figure out what are the constructors?
How about variable parameters in the constructor?
>> cin stream extraction operator is tougher to control, what would be a better way to do input?
considering z = x+y
how many operators are there?
first one is +, which object is calling + routine?
what does it return?
second one is =, who is calling =?