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;那么就什么都不能变咯。
版权说明
作者: grassofsky
出处: http://www.cnblogs.com/grass-and-moon
本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出, 原文链接 如有问题, 可邮件(grass-of-sky@163.com)咨询.