函数实参中的硬编码值是const引用吗?
Is the hard coded value in function argument a const reference?
为什么下面的程序编译失败:
#include<iostream>
using namespace std;
int fun(int &x)
{
return x;
}
int main()
{
cout << fun(10);
return 0;
}
它给出以下编译错误:从"int"类型的右值初始化"int&"类型的非const引用无效
要使它成功编译,我有两个选项:1. 我们必须使用int fun(const int &x)而不是int fun(int &x)2. int i=10; count <<Fun (i);"而不是"count <<"func (10)"
因此,如果我们将硬编码值传递给函数,它将被视为"const引用"。
我在这里吗?还是有其他原因导致上面的程序无法编译?
不能编译,因为非const左值引用不能绑定到右值。
这样想:如果fun
中的x
是一个非const左值引用,我们应该能够修改它。然而,我们传入的是整型字面值10
。修改整数字面量意味着什么?这没有意义,所以你不能。
要解决这个问题,您应该通过对const的引用来接受参数(假设您不打算在fun
中修改它):
int fun(const int &x)
相关文章:
- 将const引用参数初始化为默认参数会导致悬空引用吗
- 为什么当我为 for(auto& it : myUnorderedMap) {... = std::move(it.second)} 时,我会得到一个 const 引用?
- 将对象传递给函数而不将其包装到 std::ref 中,而参数被指定为 const 引用
- 如何在构造函数中传递 const 引用时强制编译器不接受右值
- 为什么我需要三个嵌套的大括号来调用赋值运算符,将const引用到二维数组
- 对临时对象的Const引用不会延长其生存期
- 对 const 引用参数使用默认值会导致崩溃
- 在运算符重载中使用带有 const 引用的 friend 函数
- C++通过 const 引用传递时不调用派生类函数
- 具有字符串文本构造函数的类不适用于 const 引用初始化
- 为什么要返回对小类成员的 const 引用?
- C - 最好将枚举类作为值或const引用
- RVO:返回由值传递的值,即使显式分配给 const 引用也是如此
- const引用与可变成员的对象
- 每当传递lvalue时,每当通过rvalue传递时,将const引用存储
- 对类成员而不是 getter 的 Const 引用
- 从类型 'Matrix&' 的右值初始化 类型的非 const 引用无效 'Matrix'
- 在函数中使用 const 引用参数访问函数中成员的最佳实践 C++.
- STD ::配对的const引用如何工作
- 为什么我的C 函数拒绝返回const引用