You are on page 1of 1

Overloading “<<”

• The “<<” operator is used to output to a


stream.
Intro to C++ part 8 • This defines how the class is output to
files, including stdout.
Daniel Wigdor with data from:
1. Richard Watson, notes on C++
2. Winston, P.H., “On to C++”
ISBN: 0-201-58043-8

How to do it Things to Note


• The “<<” operator is used to output to an • Note that LHS is a param, unlike previous
output stream. examples, where it was implicitly “this”.
• The return type should be the ostream • This is because the operator is defined
from the lhs. outside the ostream class.
• Template (note: first param is lhs): • Why return the lhs as the value of the
ostream& operator <<(ostream& os, right param) { statement?
statements
// ... • So this will work:
return os; cout << q << r << s;
}

Example: << for Queue


ostream& operator << (ostream& os, Queue &q) {
int n = q.Size();
os << "[";
for (int i = 0; i < n; i++) {
char c = q.Dequeue();
os << c;
q.Enqueue(c);
if (i < n-1) { os << ","; }
}
os << "]";
return os;
}

• Note we can’t access the “contents” array


directly – this is both good and bad.

You might also like