Question

I am trying to overload my ostream operator<<, and in the body of the function I want to use a for-loop. Memory is a class I made, and its internal structure is a vector. So basically, I just want to go through the vector and print out everything that's in it when I pass Memory to an output-stream.

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

Compiler says that there is no return value, in a function returning non-void.

Was it helpful?

Solution 2

With your current version:

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

If curr == 0, nothing ever gets returned. You need to always return 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!
}

OTHER TIPS

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top