我有这样一个 struct.cout,然后我有这样一个 operator<<的重载。
struct sample {
int x;
};
然后我有这个 operator<<的重载。
std::ostream &operator<<(const std::ostream &os, const sample &s) {
if (s.x == 0)
return os << "zero";
else
return os << "not zero";
}
main:
int main() {
sample sam;
sam.x = 0;
std::cout << sam << std::endl;
sam.x = 1;
std::cout << sam << std::endl;
return 0;
}
但是编译器给了我这个错误。Complile Error
我可以做什么?
你是对的,除了你的操作符签名中的一个小错误。
std::ostream &operator<<(const std::ostream &os, const sample &s)
// ^^^^^ Problem
你把输出流标记为 const
但在函数内部修改。
os << "zero";
和
os << "not zero";
因为
std::basic_ostream<CharT,Traits>::operator<<
不是 const
.
所以,去掉那个 const
代码就会工作。