首页 > 解决方案 > 'operator<<' 不匹配

问题描述

我有以下代码:

class A {
  friend std::ostream& operator<<(std::ostream &os, A &a);
};

A a() {
  return A{};
}

int main() {
  std::cout << a(); // error!
  //A aa = a(); std::cout << aa; // compiles just fine
}

在我看来, main 中的两行应该是等价的,但编译器不同意。第一行没有编译!

error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘A’)
   std::cout << a();
             ^
...200 (!) more lines of stderr...

为什么?

标签: c++gcc

解决方案


问题是您试图将临时A实例绑定到非常量引用。

friend std::ostream& operator<<(std::ostream &os, A &a);
//..
A a() {
  return A{};
}
//...
std::cout << a(); // error. Binding a temporary to a non-const

该错误在使用 g++ 编译时指出:

cannot bind non-const lvalue reference of type 'A&' to an rvalue of type 'A'

解决方案是使参数const

 friend std::ostream& operator<<(std::ostream &os, const A &a);

推荐阅读