我什么时候应该返回 std::ostream

When should I return std::ostream?

本文关键字:std ostream 返回 什么时候      更新时间:2023-10-16

每次我要创建一个像运算符这样的运算符std::string以显示值(没有运算符)时,我都会返回std::ostream,但我不知道为什么。如果std::ofstream用作函数成员运算符函数(std::cout),我该如何返回它,我应该什么时候返回,为什么?

例:

class MyClass
{
   int val;
   std::ostream& operator<<(const std::ostream& os, const MyClass variable)
  {
      os << variable.val;
  }
}

std::string

std::string a("This is an example.");
std::cout << a;

通常在重载<<时返回对ostream的引用,以允许链接。这:

s << a << b;

等效于函数调用

operator<<(operator<<(s,a),b);

并且仅在内部调用返回合适的类型作为外部调用的参数时才有效。

要实现这一点,只需通过引用获取流参数,并通过引用直接返回相同的流:

std::ostream & operator<<(std::ostream & s, thing const & t) {
    // stream something from `t` into `s`
    return s;
}

或从其他重载返回:

std::ostream & operator<<(std::ostream & s, thing const & t) {
    return s << t.whatever();
}