简体   繁体   English

如何在调用 cout 时 output 结构中的常量文本?

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

I have this struct:我有这个结构:

struct sample {
  int x;
};

and then I have this overload of 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;
}

But the compiler gives me this error: Complile Error但是编译器给了我这个错误:编译错误

What can I do?我能做些什么?

You are right except for a small error in your operator signature:你是对的,除了你的操作员签名中有一个小错误:

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

You mark the output stream as const but then modify it inside the function:您将 output stream 标记为const ,然后在 function 中对其进行修改:

os << "zero";

and

os << "not zero";

Because因为

std::basic_ostream<CharT,Traits>::operator<< is not const . std::basic_ostream<CharT,Traits>::operator<<不是const


So, remove that const and the code will work.因此,删除该const并且代码将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM