1

我正在尝试重载我的 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 的函数中没有返回值。

4

2 回答 2

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;
}
于 2013-10-28T14:15:47.430 回答
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!
}
于 2013-10-28T14:23:41.703 回答