const reference can be assigned an int?(const 引用可以分配一个 int 吗?)
问题描述
我遇到了一个代码片段
const int& reference_to_const_int = 20;
cout<<"
reference_to_const_int = "<<reference_to_const_int<<endl;
此代码编译 &执行输出:-
This code compiles & executes with output :-
reference_to_const_int = 20
这对我来说很奇怪.据我所知参考不占用内存 &它们是其他变量的别名.因此我们不能说
This is something strange in for me. As I know reference do not occupy memory & they are aliases to other variables. hence we cannot say
int& reference_to_int = 30;
以上语句不能编译给出错误:-
The above statement shall not compile giving error :-
error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’
const int&"究竟发生了什么案件?需要完整的解释.
What exactly is happening in the "const int&" case? A full explanation is desired.
请帮忙.
谢谢
推荐答案
创建了一个临时对象,将 const 引用绑定到它是合法的,但将它绑定到非 const 引用是非法的code>const 一.
A temporary is created, and it's legal to bind a const reference to it, but illegal to bind it to a non-const one.
就像:
const int& reference_to_const_int = int(20); //LEGAL
int& reference_to_const_int = int(20); //ILLEGAL
const 引用延长了临时文件的生命周期,这就是它起作用的原因.这只是语言的规则.
A const reference extends the life of a temporary, that's why this works. It's just a rule of the language.
这篇关于const 引用可以分配一个 int 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:const 引用可以分配一个 int 吗?
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
