10

我注意到将 a 分配char给 aconst int&编译,但将其分配给 aint&会产生编译错误。

char c;
int& x = c;    // this fails to compile
const int& y = c;    // this is ok

我知道这样做不是一个好习惯,但我很想知道它发生的原因。

我通过查找“分配给不同类型的引用”、“将 char 分配给 int 引用”和“const 引用和非 const 引用之间的区别”来寻找答案,并且遇到了许多有用的帖子(int vs const int&将 char 分配给 int 变量时的奇怪行为在 C 和 C++ 中将 char 转换为 int ,引用和 const 引用作为函数参数之间的区别?),但它们似乎没有解决我的问题。

如果之前已经回答过,我深表歉意。

4

3 回答 3

8
int& x = c;

在这里,编译器正在执行从charto的隐式转换。int结果临时int只能绑定到一个const引用。绑定到 aconst int&还将延长临时结果的生命周期以匹配它所绑定的引用的生命周期。

于 2012-12-08T18:23:28.320 回答
3

这种行为在标准N45278.5.3/p5.2 参考文献 [dcl.init.ref]中是合理的

5 对“cv1 T1”类型的引用由“cv2 T2”类型的表达式初始化,如下所示:

...

5.2 否则,引用应为对非易失性 const 类型的左值引用(即 cv1 应为 const),或者引用应为右值引用。[ 例子:

double& rd2 = 2.0; // error: not an lvalue and reference not const
int i = 2;
double& rd3 = i; // error: type mismatch and reference not const

—结束示例]

于 2015-12-04T17:16:57.163 回答
1

这条线的事实

const int& y = c; 

创建临时并y绑定到临时可以通过以下方式验证:

#include <iostream>

int main()
{
   char c = 10;
   const int& y = c;

   std::cout << (int)c << std::endl;
   std::cout << y << std::endl;

   c = 20;

   std::cout << (int)c << std::endl;
   std::cout << y << std::endl;

   return 0;
}

输出:

10
10
20
10

当 的值y改变时, 的值没有c改变。

于 2015-12-04T17:18:34.320 回答