跟我一起学C++之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

 

代码实例:

#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;
}
运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值