为什么以下程序无法编译:
#include<iostream>
using namespace std;
int fun(int &x)
{
return x;
}
int main()
{
cout << fun(10);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它给出了以下编译错误:从'int'类型的右值开始无效初始化'int&'类型的非const引用
为了使它成功编译,我有两个选项:1.我们必须使用"int fun(const int&x)"而不是"int fun(int&x)"2.使用"int i = 10; cout << fun(一世);" 而不是"cout << func(10)"
因此,似乎如果我们将硬编码值传递给函数,它将被视为"const引用".
我在这儿吗?还是上面的程序没有编译的其他原因?
这不会编译,因为非const左值引用无法绑定到rvalues.
以这种方式思考:如果xin fun是非const左值引用,我们应该能够修改它.但是,我们传入了整数文字10.修改整数文字应该是什么意思?这没有意义,所以你做不到.
要解决这个问题,你应该通过引用引用你的参数(假设你不打算在其中进行修改fun):
int fun(const int &x)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
875 次 |
| 最近记录: |