const的一些浅层谈论

说说const


1.const 引用

int a = 2;
const int &b = 3;
b = 3;
cout << b << endl;

常量引用,俗称。这段代码没法通过编译,因为b只是常量引用,没法通过b来修改指向的内容


2.指针const

int a = 2;
const int *b = &a;
*b = 3;
cout << *b << endl;

这样子是没法通过编译的,因为指针b是指向const,没法修改b指向的内容,他的意思和常量引用一个意思,其实看const的位置也是一样的。只是它不叫常量指针,叫做指针常量

下面这段代码和上面的代码是同一个意思,虽然const的位置少有不同

int a = 2;
 int const *b = &a;
*b = 3;
cout << *b << endl;


3.const指针

int a = 2;
int * const b = &a;
*b = 3;
cout << *b << endl;

注意这里的const的位置,这时候b是常量指针。因为是没法把b指向不同的值


另外无论是常量引用还是指针const都是假象的const,可以通过其他方式修改它指向的值。


4.const iterator 和const_iterator

const iterator是指iterator是常量,不能修改它 ,这个和int * const a 类似。

而const_iterator 是指iterator指向的是常量,这个和const int * a 类似



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值