类型转换失败,c++报错: cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int’
【代码】类型转换失败,c++报错: cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int’
·
类型转换失败,c++报错: cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int’
源码如下:
#include<iostream>
using namespace std;
void func(int& param)
{
cout << param << endl;
}
int main()
{
long long param;
func(param);
return 0;
}
编译器报错为:
error: cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int’
10 | func(param);
3:16: note: initializing argument 1 of ‘void func(int&)’
3 | void func(int& param)
| ~~~~~^~~~~
开始很好奇,为long long转为int这里会造成数据丢失,但是报错是无法把左值引用绑定到右值。
错误信息中提到“右值”是因为在 C++ 中,某些情况下,编译器会将类型不匹配的表达式视作右值。虽然 param 是个左值,但由于它的类型与函数参数不匹配,编译器无法将其视作有效的绑定。
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)