开发者

operator << overload c++

how can i overload "<<" 开发者_运维问答operator (for cout) so i could do "cout" to a class k


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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜