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 on 2012-05-22 20:28 钟谢伟 阅读(1190) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2012年5月>
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

导航

统计

常用链接

留言簿(1)

随笔档案

IT网站

My Friends

搜索

最新评论

阅读排行榜

评论排行榜