C ++函数:将非const参数传递给const引用参数 [英] c++ function: pass non const argument to const reference parameter

查看:362
本文介绍了C ++函数:将非const参数传递给const引用参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个接受const引用参数传递的函数,

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
}

此代码可以正常工作。根据C ++入门,这是什么传递给该函数的参数如下,

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;

其中i是j的别名,

我的问题是:如果i是j的同义词,并且我定义为const,则代码是:

my question is: if i is a synonym of j, and i is defined as const, is the code:

const int& i = j

const int &i = j

redcare将非const变量转换为const变量?为什么此表达式在c ++中是合法的?

redelcare a non const variable to const variable? why this expression is legal in c++?

推荐答案

引用是const,而不是对象。它不会改变对象可变的事实,但是您有一个可以修改它的对象名称( j ),还有另一个名称( i )。

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.

对于const引用参数,这意味着 main 可以修改对象(因为它使用对象的名称 j ),而 func 无法修改对象,只要它仅使用其名称 i func 可以原则上可以通过使用 const_cast ,但不要。

In the case of the const reference parameter, this means that main can modify the object (since it uses its name for it, j), whereas func 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 a const_cast, but don't.

这篇关于C ++函数:将非const参数传递给const引用参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆