const引用类型和nonconst引用类型

有一个函数的原型是void f(CString &str);

调用处的代码是f("abc");结果编译不过,函数原型改成 void f(const CString &str); 编译就可以通过。

查了一下<<C++ Primer>>,发现nonconst引用类型只可以引用相同的类型的对象,const引用类型才可以引用类型不同的对象。

附上<<C++ Primer>>的解释:

A const reference can be initialized to an object of a different type or to an rvalue , such as a literal constant:

      int i = 42;
      //  legal for const references only
      const int &r = 42;
      const int &r2 = r + i;

 

The same initializations are not legal for nonconst references. Rather, they result in compile-time errors. The reason is subtle and warrants an explanation.

This behavior is easiest to understand when we look at what happens when we bind a reference to an object of a different type. If we write

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

 

the compiler transforms this code into something like this:

      int temp = dval;          // create temporary int from the double
      const int &ri = temp;   // bind ri to that temporary

 

If ri were not const, then we could assign a new value to ri. Doing so would not change dval but would instead change temp. To the programmer expecting that assignments to ri would change dval, it would appear that the change did not work. Allowing only const references to be bound to values requiring temporaries avoids the problem entirely because a const reference is read-only.

 

A nonconst reference may be attached only to an object of the same type as the reference itself.


A const reference may be bound to an object of a different but related type or to an rvalue.

 

 

转载于:https://www.cnblogs.com/xueguangfeng/archive/2012/05/17/2506925.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值