c++功能:将非常量参数传递给常量引用参数

发布于 2025-01-02 02:44:10 字数 474 浏览 4 评论 0原文

假设我有一个接受 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

喜你已久 2025-01-09 02:44:10

引用是 const,而不是对象。它不会改变对象是可变的这一事实,但您可以通过对象的一个​​名称 (j) 来修改它,以及另一个名称 (i) )你不能通过它。

对于 const 引用参数,这意味着 main 可以修改对象(因为它使用其名称 j),而 func 无法修改该对象,只要它仅使用其名称 ifunc 原则上可以通过使用 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), 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.

可是我不能没有你 2025-01-09 02:44:10
const int &i = j;

这声明了对常量整数的引用。
使用此引用,您将无法更改它引用的整数的值。

您仍然可以使用原始变量名 j 来更改值,只是不使用常量引用 i。

const int &i = j;

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文