第2章 变量和基本类型 附3---底层const和顶层const

时间:2024-06-10 08:34:20

和英文版的对:

As we’ve seen, a pointer is an object that can point to a different object. As a result,
we can talk independently about whether a pointer is const and whether the objects
to which it can point are const. We use the term top-level const to indicate that the
pointer itself is a const. When a pointer can point to a const object, we refer to
that const as a low-level const.

-----------------------------------------------------------------

英文中说的很明显:顶层const(top-level-const)-----指针本身是一个常量; 底层const(low-level const)指针所指的对象是一个常量。

 const限定符与指针
const int * p; //const在*左边,表示*p为常量,不可更改(经由*p不能更改指针所指向的内容)
//但指针p还是变量,想怎么变都可以。这就是所谓的底层const
举例:
int b = ;
const int * p;
p = &b;
//* p = 200; //Error *p是常量,不能再对常量赋值 int * const p = &b;//在声明的同时必须初始化,const在*的右边,表示p为常量,p所指向的地址
//是不可更改的,所以当把b的地址赋值给它时,会报错。这也就是所谓的顶层const
举例:
int b = ;
int c = ;
int * const p = &b;//在声明的同时必须初始化,const在*的右边,表示p为常量,p所指向的地址
//是不可更改的,所以当把b的地址赋值给它时,会报错
//p = &c; //Error p为常量,顶层const const int *const p;//这个就相当于以上两种情况的混合体,p是常量,
//所以不能把test2的地址赋给p;同时*p也是常量,所以*p的内容不可更改;
举例:
int test1 = ;
int test2 = ;
const int * const p = &test1;
p = &test2; //Error,p是常量,所以不能把test2的地址赋给p;
*p = ; //Error,*p是常量,所以*p的内容不可更改;