运算符 <<过载 c++

发布于 2024-09-06 04:44:37 字数 56 浏览 2 评论 0 原文

我怎样才能超载“<<”运算符(用于 cout),这样我就可以对 k 类执行“cout”

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

橘香 2024-09-13 04:44:37

任何类型 T 的输出运算符的规范实现如下:

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

请注意,输出流运算符通常不是成员函数。 (这是因为二元运算符要成为成员函数,它们必须是其左侧参数类型的成员。但是,这是一个流,而不是您自己的类型。operator<< 的一些重载除外;() 对于某些内置函数,它们是输出流类的成员。)
因此,如果 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() 成员函数可以是虚拟的(并且是纯的),从而允许流式传输多态类。

如果您想要花哨并支持所有类型的流,则必须将其模板化:(

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

但是,模板不能与虚拟函数一起使用。)

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文