c++ function: pass non const argument to const reference parameter(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的同义词(别名),
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.
这篇关于c++ 函数:将非 const 参数传递给 const 引用参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:c++ 函数:将非 const 参数传递给 const 引用参数
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
