常量指针与指向常量的指针是完全不同的概念。
int *ptr=new int;//一个指向int类型的指针
const int a=1;
const int *ptr1=&a;//一个指向const int的指针
int b=1;
int *const ptr2=&b;//一个指向int类型的const指针
指针ptr1认为自己指向的是一个const int,即不能通过*ptr1来改变它所指向的对象的值
const int a=1;
const int *ptr1=&a;//一个指向const int的指针
*ptr1=2;//error!
实际上ptr1也可以指向一个int类型,不会报错,但依然不能通过*ptr1来改变它所指向的对象的值
,如果改变的话会报错
int a=1;
const int *ptr1=&a;//一个指向const int的指针
*ptr1=2;//error!
而指针ptr2是一个指向非常量对象的常量指针,const修饰的是指针修饰符*而不是int类型
ptr2在指向一个对象后,就不能指向其他的对象了
int b=1,c=2;
int *const ptr2=&b;//一个指向int类型的const指针
ptr2=&c;//error!
另外要注意的是,以下两种写法是等价的
const int *ptr3;//一个指向常量的指针
int const *ptr4;//同上
了解以上后,我们还可以声明一个指向常量的常量指针:
const int d=1;
const int *const ptr5=&d;
int const *const ptr6=&d;//同上
//或者
int const *const ptr6=ptr5;//同上