当调用cout时,我如何在struct中输出一个常量文本?

问题描述 投票:0回答:1

我有这样一个 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

我可以做什么?

c++ struct operator-overloading
1个回答
2
投票

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

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 代码就会工作。

© www.soinside.com 2019 - 2024. All rights reserved.