c++功能:将非常量参数传递给常量引用参数
假设我有一个接受 const 引用参数传递的函数,
int func(const int &i)
{
/* */
}
int main()
{
int j = 1;
func(j); // pass non const argument to const reference
j=2; // reassign j
}
这段代码工作正常。根据 C++ 入门书,传递给该函数的参数如下所示,
int j=1;
const int &i = j;
其中 i 是 j 的同义词(别名),
我的问题是:如果i 是 j 的同义词,并且 i 被定义为 const,代码是:
const int &i = j
redelcare 将非 const 变量转为 const 变量吗?为什么这个表达式在c++中是合法的?
suppose I have a function which accept const reference argument pass,
int func(const int &i)
{
/* */
}
int main()
{
int j = 1;
func(j); // pass non const argument to const reference
j=2; // reassign j
}
this code works fine.according to C++ primer, what this argument passing to this function is like follows,
int j=1;
const int &i = j;
in which i is a synonym(alias) of j,
my question is: if i is a synonym of j, and i is defined as const, is the code:
const int &i = j
redelcare a non const variable to const variable? why this expression is legal in c++?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
引用是 const,而不是对象。它不会改变对象是可变的这一事实,但您可以通过对象的一个名称 (
j
) 来修改它,以及另一个名称 (i
) )你不能通过它。对于 const 引用参数,这意味着
main
可以修改对象(因为它使用其名称j
),而func 无法修改该对象,只要它仅使用其名称
i
。func
原则上可以通过使用const_cast
创建另一个引用或指向该对象的指针来修改该对象,但事实并非如此。The reference is const, not the object. It doesn't change the fact that the object is mutable, but you have one name for the object (
j
) through which you can modify it, and another name (i
) through which you can't.In the case of the const reference parameter, this means that
main
can modify the object (since it uses its name for it,j
), whereasfunc
can't modify the object so long as it only uses its name for it,i
.func
could in principle modify the object by creating yet another reference or pointer to it with aconst_cast
, but don't.这声明了对常量整数的引用。
使用此引用,您将无法更改它引用的整数的值。
您仍然可以使用原始变量名 j 来更改值,只是不使用常量引用 i。
This declares a reference to a constant integer.
Using this reference, you won't be able to change the value of the integer that it references.
You can still change the value by using the original variable name j, just not using the constant reference i.