(1)例:1. int i=1;
const int *cptr=&i;
*cptr=2; //出错,cptr指向的是常量1
cout<<*cptr<<endl; //
2. int i=1;
const int *cptr=&i;
i=2; //正常
cout<<*cptr<<endl; //输出2
3. int i=1,tt=8;
const int *cptr=&i;
cptr=&tt; //正常
cout<<*cptr<<endl; //输出8
综上:const pointer导致的唯一结果是不能用 *cptr=..,其他均可 (cptr本身可以更改,而其指向不可改)
但上面程序没意义,const pointer指向的应该也是const int...
const int a=1;
const int *cptr=&a 或 const void *cptr=&a; //常量,指针也必为常量
注意: 指向 const 的指针常用作函数的形参。将形参定义为指向 const 的指针,确保传递给函数的实际对象在函数中不因形参而被修改。
(2)const Pointer本身值不可改,但其指向的是否可改是根据指向的对象是否为const。
int i=10,tt=88; //若为const int i=10;也出错
int *const cptr=&i;
*cptr=9; //可以
cptr=&tt; //出错
cout<<*cptr<<endl;
(3)const Pointer to a const Object 指针本身与其指向的对象均不可以改.
const int i=10;
const int *const cptr=&i;
总结:有加const的话,都是从右往左看的,即左边修饰右边的。
例:const int *cptr cptr是个int型指针, 这个int是常量
int *const cptr cptr(即指针)是const型,这个const是指向int的
const int *const cptr=&i; cptr是const型, 而第2个const是指向int的,而这个int是常量
原变量:int型 --> 指针变量 int *const p , const int *, const int *const pI=&a;
const int型 --> 指针变量const int *p, const int *const pI=&a;
附加:
1 const string str;
string const str; //两者一样
2 string s;
typedef string *pstring;
const pstring cstr1 = &s; //1种
pstring const cstr2 = &s; // 2种all three decreations are the same type
string *const cstr3 = &s; // they're all const pointers to string
(书写时一般把const放于前面,但声明时建议const置于后面,便于理解)