views:

159

answers:

1

how can i overload "<<" operator (for cout) so i could do "cout" to a class k

+16  A: 

The canonical implementation of the output operator for any type T is this:

std::ostream& operator<<(std::ostream& os, const T& obj)
{
  os << obj.get_data1() << get_data2();
  return os;
}

Note that output stream operators commonly are not member functions. (That's because for binary operators to be member functions they have to be members of their left-hand argument's type. That's a stream, however, and not your own type. There is the exception of a few overloads of operator<<() for some built-ins, which are members of the output stream class.)
Therefor, if not all data of T is publicly accessible, this operator has to be a friend of T

class T {
  friend std::ostream& operator<<(std::ostream&, const T&);
  // ... 
};

or the operator calls a public function which does the streaming:

class T {
public:
  void write_to_stream(std::ostream&);
  // ... 
};

std::ostream& operator<<(std::ostream& os, const T& obj)
{
  obj.write_to_stream(os);
  return os;
}

The advantage of the latter is that the write_to_stream() member function can be virtual (and pure), allowing polymorphic classes to be streamed.

If you want to be fancy and support all kinds of streams, you'd have to templatize that:

template< typename TCh, typename TTr >
std::basic_ostream<TCh,TTr>& operator<<(std::basic_ostream<TCh,TTr>& os, const T& obj)
{
  os << obj.get_data1() << get_data2();
  return os;
}

(Templates, however, don't work with virtual functions.)

sbi
OMG 3 seconds and you get 3 vote up?
lionbest
Where `T` is the type of the object `k` that you want to print.
MSalters
Should it not be templated to be character-type agnostic? If I wanted to use wcout with this operator, not much would happen.
DeadMG
@DeadMG: I've done you the favor. `:)`
sbi
@sbi: Good boy. Now here's your vote-up.
DeadMG
@DeadMG: `<sheepish_grin>` Thanks, mum!
sbi
josefx
@josefx: That's an excellent point, thank you. I've done that in the past, too, I just forgot to mention it. I'll add it to the answer.
sbi
+1, very nice answer
Default