const和pointers

1. const指针总是指向相同的地址,该地址是不能被改变的.

   1: int nValue = 5;
   2: int *const pnPtr = &nValue;

*pnPtr = 6; 这样的操作是可行的;而 int nValue2 = 2; pnPtr = &nValue2;这样的操作是不可行的。

int *const pnPtr 可以这么理解,pnPtr当作地址,该指针有const地址,并且指向一个整型变量。

2. 指向const变量(虽然这个变量本身可以不是const的)的指针

   1: int nValue = 5;
   2: const int *pnPtr = &nValue;

const int *pnPtr可以这么理解,一个可以改变地址的指针指向的是一个不能改变大小的变量。

也就是说,*pnPtr = 6;这样是不行的;int nValue2 = 6; pnPtr = &nValue2;这样是可行的

3. 当然,还有一种就是两者都不能改变了。

int nValue = 2;

const int *const pnPtr = &nValue;

不过此时可以通过nValue=6;来改变*pnPtr的值。把int nValue = 2;改成 const int nValue = 2;那么就什么都不能变咯。

posted @ 2012-05-22 20:48  grassofsky  阅读(167)  评论(0编辑  收藏  举报