调用 cout 时如何在结构中输出常量文本?

How I can output a constant text in struct when call cout?

本文关键字:输出 常量 文本 结构 cout 调用      更新时间:2023-10-16

我有这个结构:

struct sample {
int x;
};

然后我有这个运算符重载<<:

std::ostream &operator<<(const std::ostream &os, const sample &s) {
if (s.x == 0)
return os << "zero";
else
return os << "not zero";
}

主要:

int main() {
sample sam;
sam.x = 0;
std::cout << sam << std::endl;
sam.x = 1;
std::cout << sam << std::endl;
return 0;
}

但是编译器给了我这个错误: 编译错误

我能做什么?

你是对的,除了你的操作员签名中的一个小错误:

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,代码将起作用。