函数参数中的硬编码值是const引用吗?

时间:2015-06-05 08:45:47

标签: c++

为什么以下程序无法编译:

#include<iostream>
using namespace std;

int fun(int &x)
{
    return x;
}
int main()
{
    cout << fun(10);
    return 0;
}

它给出了以下编译错误: 类型&#39; int&amp;&#39;的非const引用的无效初始化来自类型&#39; int&#39;

的右值

为了使编译成功,我有两个选择: 1.我们必须使用&#34; int fun(const int&amp; x)&#34;而不是&#34; int fun(int&amp; x)&#34; 2.使用&#34; int i = 10; cout&lt;&lt;有趣的(ⅰ);&#34;而不是&#34; cout&lt;&lt; func(10)&#34;

所以,似乎如果我们将一个硬编码值传递给一个函数,它将被视为&#34; const reference&#34;。

我在这儿吗?或者上述程序是否还有其他原因无法编译?

1 个答案:

答案 0 :(得分:5)

这不会编译,因为非const左值引用无法绑定到rvalues。

以这种方式思考:如果<dependency> <groupId>com.datastax.spark</groupId> <artifactId>spark-cassandra-connector_2.10</artifactId> <version>1.3.0-M1</version> </dependency> 中的x是非const左值引用,我们应该能够修改它。但是,我们传入了整数文字fun。修改整数文字应该是什么意思?这没有意义,所以你不能。

要解决这个问题,你应该通过引用来引用你的参数(假设你不打算在10中修改它):

fun