C++ 与‘不匹配;操作员<<’;

C++ 与‘不匹配;操作员<<’;,c++,gcc,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 } A类{ friend st

我有以下代码:

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
}
A类{

friend std::ostream&operator问题是您试图将一个临时
实例绑定到一个非常量引用

friend std::ostream& operator<<(std::ostream &os, A &a);
//..
A a() {
  return A{};
}
//...
std::cout << a(); // error. Binding a temporary to a non-const
解决方案是使参数
常数

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

friend std::ostream&operatry将第二个参数设为
const
引用。无论如何,您应该从一开始就这样做。您还应该发布更多的错误消息,因为它应该清楚地说明问题所在。您可以将const引用绑定到临时参数:例如:
const int&=7;
有效,但您可以无法将普通引用绑定到临时值或常量。(右值)。例如:
int&r=7;
//错误。因此,在您的示例中,提取运算符接受类
a
的普通引用,因此您只能向其传递非常量左值引用。由于按值返回的函数返回右值,因此代码失败。
cannot bind non-const lvalue reference of type 'A&' to an rvalue of type 'A'
 friend std::ostream& operator<<(std::ostream &os, const A &a);