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

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

我有这个结构:

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

但是编译器给我这个错误: 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 代码即可。