我有以下代码:
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
}
Run Code Online (Sandbox Code Playgroud)
在我看来,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...
Run Code Online (Sandbox Code Playgroud)
为什么?
问题是您正在尝试将临时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
Run Code Online (Sandbox Code Playgroud)
使用g ++编译时,错误指出:
cannot bind non-const lvalue reference of type 'A&' to an rvalue of type 'A'
Run Code Online (Sandbox Code Playgroud)
解决方案是使参数const:
friend std::ostream& operator<<(std::ostream &os, const A &a);
Run Code Online (Sandbox Code Playgroud)