const reference 关键字 示例 代码



#include <iostream>
using std::cout;
using std::endl;

int main()
{
int i = 5;
const int ic =10;
const int *pic = &i;//从右往左定义“pic 是一个指向int类型的、被定义成const对象的指针”
i = i+1;
pic = pic + 1;
// *pic = 2; Error *pic 不能做左值
const int *pic_1 = &ic;
pic_1 = pic_1 + 1;

const int * const pic_2 = &ic; //pic_2 是一个指向const int类型的、被定义成const对象的指针
i = i + 1;
// pic_2 = pic_2 + 1;// error assignment of read-only variable 'pic_3'
// *pic_2 = 2; //Error *pic_2 不能做左值

const int * const pic_3 = &i;
i = i+1;
// pic_3 = pic_3 + 1; error assignment of read-only variable 'pic_3'
//*pic_3 = 2; //Error *pic_2 不能做左值

// int * const cpi = &ic; // cpi是一个指向 const int类型,被定义为非const对象的指针

int * const cpi_1 = &i; //cpi_1是一个指向const int 类型,被定义为非const对象的指针
*cpi_1 = 10;
// cpi = cpi + 1;

return 0;
} //End of main





#include <iostream>
using std::cout;
using std::endl;

int main()
{
int ival = 0;
const int ival3 = 1;
const int &rval1 = 1.01;
int &rval2 = ival;
int * const &rval3 = &ival;
int *pi = &ival;
int * &rval4 = pi;
int &rval5 = *pi;

//int &* prval1 = pi;//error: cannot declare pointer to 'int&'
int * & prval1 = pi;//right

const int & ival2 = 1;

//const int * & prval2 = &ival3;//error: cannot bind non-const lvalue reference of type 'const int*&' to an rvalue of type 'const int*'
const int * const & prval2 = &ival3;

//int * & prval3 = &ival;//error: cannot bind non-const lvalue reference of type 'int*&' to an rvalue of type 'int*'
const int * & prval3 = &ival;//error: cannot bind non-const lvalue reference of type 'int*&' to an rvalue of type 'int*'
//const int * const & prval3 = &ival1;
return 0;
} //End of main
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值