【问题标题】:ostream overloading with for loop, no return valueostream用for循环重载,没有返回值
【发布时间】:2013-10-28 14:14:39
【问题描述】:

我正在尝试重载我的 ostream 运算符

std::ostream& operator<<(std::ostream& out, const Memory& mem) 
{
    int curr(mem.get_current());
    for (int i = 0; i <= curr; ++i) 
    {    
        return out << mem.mem_[i] << std::endl;
    }
}

编译器说没有返回值,在一个返回非void的函数中。

【问题讨论】:

    标签: c++ for-loop vector operator-keyword ostream


    【解决方案1】:
    std::ostream& operator<<(std::ostream& out, const Memory& mem) {
      int curr(mem.get_current());
      for (int i = 0; i <= curr; ++i) {
        out << mem.mem_[i] << std::endl;
      }
      return out;
    }
    

    【讨论】:

    • @JN11 我的答案中的代码中显然有一个返回值。
    • 你是对的,愚蠢的错误。我现在感觉很笨:p 无论如何谢谢
    【解决方案2】:

    使用您当前的版本:

    std::ostream& operator<<(std::ostream& out, const Memory& mem) 
    {
        int curr(mem.get_current());
        for (int i = 0; i <= curr; ++i)
        {    
            return out << mem.mem_[i] << std::endl;
        }
    }
    

    如果curr == 0,则不会返回任何内容。您需要始终返回out

    std::ostream& operator<<(std::ostream& out, const Memory& mem) 
    {
        int curr(mem.get_current());
        for (int i = 0; i <= curr; ++i) 
        {    
            out << mem.mem_[i] << std::endl;
        }
        return out; // outside the loop, so it always gets returned!
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-13
      • 1970-01-01
      • 2020-01-07
      • 2011-11-25
      • 2016-09-03
      • 1970-01-01
      • 1970-01-01
      • 2016-08-23
      相关资源
      最近更新 更多