ostream 重载与 for 循环,无返回值

ostream overloading with for loop, no return value

本文关键字:返回值 循环 for 重载 ostream      更新时间:2023-10-16

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

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

使用当前版本:

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