The operator << C ++ overload

how can I overload the "<<statement (for cout), so I could make" cout "to class k

+3
source share
1 answer

The canonical implementation of the output operator for any type Tis as follows:

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

, -. ( , , -, . , . operator<<() -ins, .)
, T , T

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

, :

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;
}

, - write_to_stream() virtual ( ), .

, :

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;
}

( , .)

+17

Source: https://habr.com/ru/post/1750498/


All Articles