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
代码实例:
#include<iostream>
usingnamespace std;
//const引用是指向const对象的引用
int main(void)
{
constint val = 1024;
constint& refval = val;
//int& ref2 = val; // Error,nonconst reference to const object
//refval = 200; Error,refval是一个常量
int val2 = 1024;
constint& ref3 = val2; //const reference to nonconst object const引用可以指向普通变量
double val3 = 3.14;
constint& ref4 = val3; // 等价于:int temp = val3; const int& ref4 = temp;
cout<<"ref4="<<ref4<<endl;
cout<<"val3="<<val3<<endl;
//int& ref5 = val3; Error
return 0;
}
运行结果: