c++ - '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...
为什么?
解决方案
问题是您试图将临时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);
推荐阅读
- python - 如何运行包内的 shell 脚本?
- reactjs - AWS Amplify / Dynamo - 作为字符串数组返回的对象数组
- c++ - 使用 C++20 概念实现 Pair 概念
- python - 使用循环反转字符串的函数
- python-3.x - How can I save a PNG image greater than 90 KB?
- java - Elasticsearch Java API:[eventDefinitions] 的对象映射尝试将字段 [null] 解析为对象,但找到了具体值?
- node.js - 如何编译 JSX 服务器端
- php - 单击删除按钮时,我必须单击两次才能将删除请求发布到 MYSQL Server
- python - 从分割的平铺图像拼接回 label_image 数组
- python - 在 opencv2 中加载 ONNX 模型失败并出现 blob.type() 断言错误