12-3-13c++中关于const的应用

本文详细解析了C++中const修饰符的应用场景,包括const_iterator的使用限制、const指针与指向const对象的指针的区别,以及typedef与const结合使用时的注意事项。

1关于const_iterator

当我们对const_iterator解引用时,可以得到一个指向const对象的引用,同任何常量一样,该对象不可重写。

例子:vector<int>::const_iterator iter=text.begin();

*iter=9;//这里是错误的,该迭代器指向的对象为const对象,不可更改。

2 声明一个const类型的iterator

vector<int> num(10);

const vector<int>::iterator iter=num.begin();

 iter++; //error,can not chang the value of iter

*iter=10; //ok can change its underlying element

3.指向const对象的指针。

const char * cptr;

表明cptr指向的是一个const对象,不可随意更改。类似上面的const_iterator

4.const指针。

int errNumb=0;

int * const curErr=&errNumb;

表明curErr不可再指向其他地址了。


5指针与typedef

typedef string *pstring;

const pstring cstr;

一旦指针域typedef结合,千万别简单的认为文本扩展了。

正确分析:cstr是一个const pstring类型。在第一句中pstring为指向string对象的指针,经过const之后

意思是将cstr声明为指向string对象的const指针。

下面是关于其等价表达式:

----string *const cstr;

--typedef string *pstring;

  pstring const cstr;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值