C++ in 21 days ONE---Using const Pointers

You can use the keyword const for pointers before the type, after the type, or in both
places. For example, all the following declarations are legal:
const int * pOne;
int * const pTwo;
const int * const pThree;
Each of these, however, does something different:
n pOne is a pointer to a constant integer. The value that is pointed to can’t be
changed.
n pTwo is a constant pointer to an integer. The integer can be changed, but pTwo can’t
point to anything else.
n pThree is a constant pointer to a constant integer. The value that is pointed to can’t
be changed, and pThree can’t be changed to point to anything else.
The trick to keeping this straight is to look to the right of the keyword const to find out
what is being declared constant. If the type is to the right of the keyword, it is the value
that is constant. If the variable is to the right of the keyword const, it is the pointer vari-
able itself that is constant. The following helps to illustrate this:
const int * p1;  // the int pointed to is constant
int * const p2;  // p2 is constant, it can’t point to anything else

ps:在delete 一个指针后并设置这个指针为NULL或者0有额外好处。再次delete同一个指针时不会引起错误。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值