在C ++中将char赋值给int引用和const int引用

时间:2012-12-08 18:21:09

标签: c++ reference casting const c++03

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

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

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

我通过寻找“分配给不同类型的引用”,“将char分配给int引用”和“const引用与非const引用之间的区别”来寻找答案,并且遇到了许多有用的帖子(int vs const int&Weird behaviour when assigning a char to a int variableConvert char to int in C and C++Difference between reference and const reference as function parameter?),但它们似乎没有解决我的问题。

如果以前已经回答过,我道歉。

3 个答案:

答案 0 :(得分:8)

int& x = c;

此处编译器正在执行从charint的隐式转换。生成的临时int只能绑定到const引用。绑定到const int&也会延长临时结果的生命周期,以匹配绑定的引用的生命周期。

答案 1 :(得分:3)

此行为在标准N4527 8.5.3 / p5.2参考文献[dcl.init.ref]

中是合理的
  

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

     

...

     

5.2否则,引用应为a的左值引用   非易失性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
     

- 结束示例]

答案 2 :(得分: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的值没有变化。

相关问题