就像正常的变量,指针可以声明常数。有指针和const可以混合使用两种不同的方式,和他们混起来很容易。
声明一个常量指针,使用const关键字星号和指针之间的名字:
1
2
int nValue = 5;
int *const pnPtr = &nValue;
就像一个正常的const变量,const指针必须初始化为一个价值申报后,其价值是无法改变的。这意味着一个const指针总是指向相同的值。在上述案例中,pnptr总是指向值的地址。然而,因为被指价值仍然是非const对象,它有可能改变的值被指出通过指针解引用:
1
*pnPtr = 6; // allowed, since pnPtr points to a non-const int
它也可以声明一个指向常量的指针变量的数据类型使用const之前。|
1
2
int nValue = 5;
const int *pnPtr = &nValue;
注意到一个恒定的变量的指针不实际上必须指向一个变量!相反,这样想:一个指向一个变量,将变为常数时,它是通过指针访问。
1
nValue = 6; // nValue is non-const