C++中的引用和常量混淆
reference and const confusion in C++
我知道引用只是一个变量的另一个名字,它们在内存中并不作为一个单独的对象存在,但是这里发生了什么
double i = 24.7;
const int &ri = i; //notice int here
std::cout << i << std::endl; //prints 24.7
i = 44.4;
std::cout << ri << std::endl; // prints 24
std::cout << i << std::endl; //prints 44.4
我的问题是 ri
是什么的别名? [某处内存中的值 24]
您不能直接将引用绑定到不同类型的对象。
对于const int &ri = i;
,首先需要将i
转换为int
,然后创建一个临时的int
,再绑定到ri
,它与原始对象无关 i
.
顺便说一句:lifetime of the temporary 已扩展以匹配此处引用的生命周期。
BTW2:临时只能绑定到 const
或右值引用的左值引用。
我知道引用只是一个变量的另一个名字,它们在内存中并不作为一个单独的对象存在,但是这里发生了什么
double i = 24.7;
const int &ri = i; //notice int here
std::cout << i << std::endl; //prints 24.7
i = 44.4;
std::cout << ri << std::endl; // prints 24
std::cout << i << std::endl; //prints 44.4
我的问题是 ri
是什么的别名? [某处内存中的值 24]
您不能直接将引用绑定到不同类型的对象。
对于const int &ri = i;
,首先需要将i
转换为int
,然后创建一个临时的int
,再绑定到ri
,它与原始对象无关 i
.
顺便说一句:lifetime of the temporary 已扩展以匹配此处引用的生命周期。
BTW2:临时只能绑定到 const
或右值引用的左值引用。