我有以下代码:
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/