c++ 函数:将非 const 参数传递给 const 引用参数

2022-01-23 00:00:00 pass-by-reference constants c++

假设我有一个接受 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的同义词(别名),

in which i is a synonym(alias) of j,

我的问题是:如果 i 是 j 的同义词,并且 i 被定义为 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

redelcare 一个非 const 变量到 const 变量?为什么这个表达式在 c++ 中是合法的?

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

推荐答案

引用是常量,不是对象.它不会改变对象是可变的这一事实,但是您有一个可以修改它的对象名称 (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.

相关文章