指针和const限定符

时间:2021-01-26 20:21:36

1、指向const对象的指针

const double pi = 3.14;

double *ptr = π        //error:ptr is a plain pointer

const double *cptr = π    //ok:cptr is a pointer to const

不能用void *指针保存const对象的地址,而必须使用const void *类型的指针保存const对象的地址

const int universe = 42;

const void *cpv = &universe;    //ok:cpv is const

void *pv = &universe;        //error:universe is const

允许把非const对象的地址赋给指向const对象的指针

double dval = 3.14;          //dval is a double;its value can be changed

const double *cptr = &dval;      //ok:but can't change dval through cptr

尽管dval不是const对象,但任何企图通过指针cptr修改其值的行为都会导致编译时的错误。

2、const指针

3、指向const对象的const指针

4、指针和typedef

typedef string *pstring;

const pstring cstr;

声明const pstring时,const修饰的是pstring的类型,这是一个指针。因此,该声明语句应该是把cstr定义为指向string类型对象的const指针,这个定义等价于string *const cstr;    //equivalent to const pstring cstr

用typedef写const类型定义时,const限定符加在类型名前面容易引起对所定义的真正类型的误解:

string s;

typedef string *pstring;

const pstring cstr1 = &s;    //written this way the type is obscured

pstring const cstr2 = &s;    //all three decreations are the same type

string *const cstr3 = &s;    //they're all const pointers to string