【问题标题】:'operator<<' must return value?'operator<<' 必须返回值?
【发布时间】:2021-05-19 15:21:35
【问题描述】:
从此代码块获取 Visual Studio 2019 中的编译器错误 c4716('operator
// Friend function to print the towers to stream
ostream& operator<<(ostream& stream, const TheGame& game) {
stream
<< "Tower #0:" << game.towers[0] << endl
<< "Tower #1:" << game.towers[1] << endl
<< "Tower #2:" << game.towers[2] << endl
;
}
任何帮助将不胜感激,谢谢!
【问题讨论】:
标签:
visual-c++
compiler-errors
【解决方案1】:
您的代码中没有任何值的return。正如错误所说,您的operator<< 必须返回一个值(在您的情况下可能是原始流,因此可以将更多流操作链接到它,即return stream;)。
2 << 3 例如会返回16。而stream << something 通常会返回stream,以便您可以在其返回值的末尾添加更多<< 操作。由于您正在实施自己的 operator<<,因此您也需要注意这一点。
【解决方案2】:
// Friend function to print the towers to stream
ostream& operator<<(ostream& stream, const TheGame& game) {
return stream
<< "Tower #0:" << game.towers[0] << endl
<< "Tower #1:" << game.towers[1] << endl
<< "Tower #2:" << game.towers[2] << endl
;
}