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
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01