用for循环重载ostream,没有返回值

时间:2013-10-28 14:14:40

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

我正在尝试重载我的ostream运算符<<,并且在我想要使用for循环的函数体中。记忆是我制作的一个类,它的内部结构是一个向量。所以基本上,我只是想通过向量并打印出将内存传递给输出流时所有内容。

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的函数中没有返回值。

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

使用您当前的版本:

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