常量 const 和 指针
const对象只能访问const成员函数,而非const对象可以访问任意的成员函数,包括const成员函数;
const对象的成员是不能修改的,而通过指针维护的对象确实可以修改的;
const成员函数不可以修改对象的任何非stastic数据,不管对象是否具有const性质。编译时以是否修改成员数据为依据进行检查。
const成员函数不能调用非const成员函数,因为非const成员函数可以会修改成员变量
声明指针时,可以在类型前或后使用关键字const,也可在两个位置都使用。三种定义形式如下:
- Pointer to constant
- const int *ptr;
- int const *ptr;
- Constant pointer to variable
- int *const ptr;
- constant pointer to constant
- const int *const ptr;
各个含义如下:
- const int * pOne;
- You cannot change the value pointed by ptr, but you can change the pointer itself.
- int * const pTwo;
- You cannot change the pointer p, but can change the value pointed by ptr.
- const int *const pThree;
- You can neither change the value pointed by ptr nor the pointer ptr.
加深记忆记住三句话:
指针和 const 谁在前先读谁 ;
*象征着地址,const象征着内容;
谁在前面谁就不允许改变。
例如:
int const *p1 = &b; //const 在前,定义为常量指针
int *const p2 = &c; // *在前,定义为指针常量