c++ - 与 ‘operator<<’ 不匹配

标签 c++ gcc

我有以下代码:

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...

为什么?

最佳答案

问题在于您正在尝试将临时 A 实例绑定(bind)到非常量引用。

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

关于c++ - 与 ‘operator<<’ 不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57128595/

相关文章:

c++ - 为程序分配内存的最佳方式

c++ - C/C++ 预处理器中宽字符串文字的宏参数字符串化

c++ - 显式模板特化的语法

gcc - arm-linux-gnueabihf-gdb 与 gdb-multiarch

gcc - 如何禁用警告: null character(s) preserved in literal?

gcc - 如何防止 Qt Creator 为同一个库生成多个 .so 文件?

c++ - 什么标准对临时继承人进行静态转换?

gcc - 无法配置 gcc - 找不到 mpfr

windows - OpenACC 与 OpenMP

c++ - Visual Studio 包含文件调用错误 - C++