20-CS-122-001 Computer Science II Spring 2012
Operator Overloading

Virtual functions, classes, inheritance, lists, queues, stacks, applications

Prev      Next      Lectures

Overloading stream input and output

   Output Stream:

       ostream &operator <<(ostream &out, Fraction &frac) {
          out << frac.num << '/' << frac.denom;
          return out;
       }


       class Fraction {
          friend ostream &operator <<(ostream &, Fraction &);
          ...


       Fraction r(1,2), s(-3,4);
       ...
       cout << r << " , " << s << '\n';

   Output Stream:

       ostream &operator <<(ostream &out, Fraction &frac) {
          frac.display(out);
          return out;
       }


       void Fraction::display(ostream &out = cout) {
          out << num << '/' << denom;
       }