【问题标题】:assigning char to int reference and const int reference in C++在 C++ 中将 char 分配给 int 引用和 const int 引用
【发布时间】:2012-12-08 18:21:09
【问题描述】:

我注意到将 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?),但他们似乎没有解决我的问题。

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

【问题讨论】:

  • @downvoter 你介意解释一下原因吗?我想在这里学习如何提高我的问题的质量,因为我计划定期访问这个网站。 :)

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


【解决方案1】:
int& x = c;

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

【讨论】:

  • 感谢您的精彩解释。
【解决方案2】:

这种行为在标准N4527 中是合理的,在 8.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

—结束示例]

【讨论】:

    【解决方案3】:

    事实是行

    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
    

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

    【讨论】:

      猜你喜欢
      • 2013-10-15
      • 1970-01-01
      • 2018-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 2012-12-10
      • 1970-01-01
      相关资源
      最近更新 更多