牛骨文教育服务平台(让学习变的简单)
博文笔记

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

创建时间:2010-12-08 投稿人: 浏览次数:469

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同一个指针时不会引起错误。

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。