我注意到将 char
分配给 const int&
可以编译,但是将其分配给 int&
会出现编译错误。
char c;
int& x = c; // this fails to compile
const int& y = c; // this is ok
我知道这样做不是一个好的做法,但我很想知道它发生的原因。
我通过寻找“分配给不同类型的引用”、“将 char 分配给一个 int 引用”和“const 引用和非常量引用之间的区别”来寻找答案,并遇到了许多有用的帖子( 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? ),但它们似乎没有解决我的问题。
如果之前已经回答过这个问题,我深表歉意。
最佳答案
int& x = c;
编译器正在执行从 char
到 int
的隐式转换。生成的临时 int
只能绑定(bind)到 const
引用。绑定(bind)到 const int&
还将延长临时结果的生命周期,以匹配它所绑定(bind)到的引用的生命周期。
关于c++ - 在 C++ 中将 char 分配给 int 引用和 const int 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13780417/