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

C++ 如何在调用cout时在struct中输出常量文本?,c++,struct,operator-overloading,cout,C++,Struct,Operator Overloading,Cout,我有这个结构: struct sample { int x; }; 然后我有一个超负荷的操作符你是对的,除了你的操作符签名中有一个小错误: std::ostream &operator<<(const std::ostream &os, const sample &s) // ^^^^^ Problem 及 os从操作员签名中的const std::ostream&os中删除const。此外,您还需要返回os

我有这个结构:

struct sample {
  int x;
};

然后我有一个超负荷的操作符你是对的,除了你的操作符签名中有一个小错误:

std::ostream &operator<<(const std::ostream &os, const sample &s)
//                       ^^^^^ Problem


os从操作员签名中的
const std::ostream&os
中删除
const
。此外,您还需要
返回os在例程的末尾。
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
os << "zero";
os << "not zero";