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 引用参数


基础教程推荐
- C++,'if' 表达式中的变量声明 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 设计字符串本地化的最佳方法 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01