问题描述
在 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
;
}
任何帮助将不胜感激,谢谢!
解决方法
您的代码中没有带有任何值的 return
。正如错误所说,您的 operator<<
必须返回一个值(可能是您的情况下的原始流,因此可以将更多流操作链接到它,即 return stream;
)。
2 << 3
将返回 16
。而 stream << something
通常返回 stream
以便您可以在其返回值的末尾添加更多 <<
操作。由于您要实现自己的 operator<<
,因此您也需要注意这一点。
// 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
;
}