SLIDE 6 6
Operator overloading
- Global operator definitions
friend Complex operator+( Complex &c1, Complex &c2 ); friend Complex operator-(Complex &c1); friend bool operator== (const Complex &c1, const Complex &c2); friend Complex& operator+= (Complex &c1, const Complex &c2); friend Complex& operator+= (Complex &c, double d);
Insertion and Extraction – writing your own
- Recall how operators work:
Point P (0,0); cout << P;
is the same as:
cout.operator<< (P);
however, who can predict the need for an
Insertion and Extraction – writing your own
- Instead, the compiler looks for:
– operator<<( cout, P );
- Note that this can’t be a member of Point
since cout is the first argument.
- Take home message: operator<< and
- perator>> are defined outside of a
class.
Writing an inserter (operator<<)
1. The first argument should be a reference to an
- stream. The second argument should be a constant
reference to your class. 2. The function should return a reference to an ostream so that insertions can be chained. 3. The body of the function should perform whatever
- utput is appropriate for your class, but nothing more!
4. If you need to access the private data members of your class directly, then your class must declare this function to be a friend
Writing an inserter (operator<<)
friend ostream &operator<<( ostream &out, const Point &p ) {
- ut << ’(’ << p.x << ’,’ << p.y << ’)’;
return out; }
Output:
(0,0)
Writing an extractor (operator>>)
– Must handle possible errors – Argument cannot be const reference. – Almost surely will have to declare as a friend.