const int * p(int和const位置交换是一样的)
首先,明白一个概念 – 指向常量的指针。比如:const int *pt; 这说明:
pt是指向int型常量的指针 !!! pt只是个const int型指针!!!
它的值 pt会改变,但是它指向的值不能变 。
int * const p
从右向左看,p为常量,且一个int*的指针。p的值无法改变,但是p指向的值可以改变。
int a=10;
int b=11;
int * const p=&a;
p=&b;//错误,p只能指向a,p是个常量,不能变
*p=12;//正确,此时a的值变为12
三种指向
//指向常量指针-->变量 指针值可变,指向的量的值不可变
int age=39;
int wage=20000;
const int *p=&a;
cout<<"p的值为:"<<p;
p=&wage;
cout<<"p的值为:"<<p;
*p=66666;//错误,不能改wage的值
运行如下:
继续
//指向const指针-->常量 个人感觉意义不大
const int a=8;
const int *pt=&a;
//常规指针-->const量 是不可以的
const int b=1;
int *pt=&b;//pt指向的值可以改变,这与b是常量显然矛盾
常量数组
禁止将常量数组的地址赋给非常量指针:常量数组名 不能作为参数 传给非常量的形参:
比如 const int num[3]={1,2,3};
int sum(int arr[], int n);
…
int j= sum( num, 3);
以上是绝对不行的!!!
总结:尽可能使用const
在函数参数里将指针声明为指向常量的指针有两个好处:
1)避免无意间修改数据带来的错误;
2)能够处理const和非const实参。