美文网首页程序员
Initialization and References to

Initialization and References to

作者: muye2010 | 来源:发表于2017-01-24 08:34 被阅读0次

    今天读到《C++ Primer》第五版第2.4.1节 References to const 讲到了引用和被引用的对象类型必须匹配的第一个例外,就是有const关键字存在的情况。书中是这样描述的:

    The first exception is that we can initialize a reference to const from any expression that can be converted to the type of the reference

    后面举了一个例子:

    double dval = 3.14;
    const int &ri = dval;
    

    当将引用绑定到与当前引用类型不同的一个对象时,编译器做了如下操作:

    const int temp = dval;
    const int &ri = temp;
    

    也就是用一个临时变量存储类型转换后的值。
    如果编译器允许这种写法int &ri = dval;那么ri = 3;只会使得临时变量的值发生变化,并不会影响dval的值,所以这样操作是没有意义的,结果是编译器判定这样的写法为非法。结论是对于引用类型和被引用对象类型不一致的情况(前提是可相互转换),必须使用const关键字。

    相关文章

      网友评论

        本文标题:Initialization and References to

        本文链接:https://www.haomeiwen.com/subject/zgagbttx.html