问题描述
我注意到将 char
分配给 const int&
可以编译,但将其分配给 int&
会导致编译错误.
I noticed that assigning a char
to a const int&
compiles, but assigning it to a int&
gives a compilation error.
char c;
int& x = c; // this fails to compile
const int& y = c; // this is ok
我知道这样做不是一个好的做法,但我很想知道发生这种情况的原因.
I understand that it is not a good practice to do this, but I am curious to know the reason why it happens.
我通过寻找分配给不同类型的引用"、将 char 分配给 int 引用"和常量引用和非常量引用之间的差异"来搜索答案,并遇到了许多有用的帖子(int vs const int& , 将字符分配给 int 变量时的奇怪行为 , 在 C 和 C++ 中将 char 转换为 int ,引用和作为函数参数的常量引用之间的区别?),但它们似乎没有解决我的问题.
I have searched for an answer by looking for "assigning to reference of different type", "assigning char to a int reference", and "difference between const reference and non-const reference", and came across a number of useful posts (int vs const int& , Weird behaviour when assigning a char to a int variable , Convert char to int in C and C++ , Difference between reference and const reference as function parameter?), but they do not seem to be addressing my question.
如果之前已经回答过这个问题,我深表歉意.
My apologies if this has been already answered before.
推荐答案
int& x = c;
此处由编译器执行从 char
到 int
的隐式转换.生成的临时 int
只能绑定到 const
引用.绑定到 const int&
还将延长临时结果的生命周期以匹配它所绑定到的引用的生命周期.
Here an implicit conversion from char
to int
is being performed by the compiler. The resulting temporary int
can only be bound to a const
reference. Binding to a const int&
will also extend the lifetime of the temporary result to match that of the reference it is bound to.
这篇关于在 C++ 中将 char 分配给 int 引用和 const int 引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!