【问题标题】:When should I return std::ostream?我应该什么时候返回 std::ostream?
【发布时间】:2014-01-14 15:02:37
【问题描述】:

每次我要创建像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;

【问题讨论】:

  • 请至少给出具体的例子。你问的不是很清楚。
  • “字符串运算符”,使用“ofstream 作为函数”???这到底是什么意思?
  • @texasbruce 当我说std::ofstream 作为一个函数时,我的意思是std::cout &lt;&lt; variable(见编辑)。
  • 如果你的意思是使用ofstream对象的成员运算符函数,那可能是一个更好的说法。
  • 如果通过引用传递,通常会返回一个参数,并且您想chain-it-up函数调用。

标签: c++ std ostream


【解决方案1】:

当重载&lt;&lt; 时,通常会返回对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();
}

【讨论】:

    猜你喜欢
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-08
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多