const引用与非const引用

六月ゝ 毕业季﹏ 提交于 2019-12-10 04:26:15

 const引用可读不可改,与绑定对象是否为const无关,注意区分const引用与对const对象的引用

非const引用可读可改,只可与非const对象绑定

const int ival = 1024;

const int &refVal = ival; // ok: both reference and object are const

int &ref2 = ival;            // error: nonconst reference to a const object

 

const引用只能绑定到与该引用同类型的对象。

const引用则可以绑定到不同但相关的类型的对象或绑定到左值。

const引用可以初始化为不同类型的对象或者初始化为右值,如字面值常量:

int i = 42;

// legal for const references only

const int &r = 42;

const int &r2 = r + i;//同样的初始化对于非const引用却是不合法的,而且会导致编译时错误

double dval = 3.14;

const int &ri = dval;

编译器会把这些代码转换成如以下形式的编码:

int temp = dval;          // create temporary int from the double

const int &ri = temp;   // bind ri to that temporary

 

const int t = 9;
const int& k = t;
cout<<&k<<endl;
cout<<&t<<endl;

输出是

0012FF6C
0012FF74

  int t = 9;
int& k = t;
cout<<&k<<endl;
cout<<&t<<endl;

输出是

0012FF74
0012FF74

如果是对一个常量进行引用,则编译器 首先建立一个临时变量,然后将该常量的值置入临时变量中,对该引用的操作就是对该临时变量的操作。
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!