The document discusses overloading the "<<" operator to define how a class is output to streams like stdout. It notes that the "<<" operator is used to output to an output stream, with the left-hand side as a parameter. The return type should be the output stream from the left-hand side. An example shows overloading "<<" for a Queue class to output its contents between brackets with commas between elements.
The document discusses overloading the "<<" operator to define how a class is output to streams like stdout. It notes that the "<<" operator is used to output to an output stream, with the left-hand side as a parameter. The return type should be the output stream from the left-hand side. An example shows overloading "<<" for a Queue class to output its contents between brackets with commas between elements.
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; }