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

和英文版的对:

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)指针所指的对象是一个常量。

 1 const限定符与指针
 2         const int * p;         //const在*左边,表示*p为常量,不可更改(经由*p不能更改指针所指向的内容)
 3                      //但指针p还是变量,想怎么变都可以。这就是所谓的底层const
 4         举例:
 5         int b = 22;
 6         const int * p;
 7         p = &b;
 8         //* p = 200;        //Error *p是常量,不能再对常量赋值
 9 
10         
11         int * const p = &b;//在声明的同时必须初始化,const在*的右边,表示p为常量,p所指向的地址
12                           //是不可更改的,所以当把b的地址赋值给它时,会报错。这也就是所谓的顶层const
13         举例:
14         int b = 33;
15         int c = 22;
16         int * const p = &b;//在声明的同时必须初始化,const在*的右边,表示p为常量,p所指向的地址
17                           //是不可更改的,所以当把b的地址赋值给它时,会报错
18         //p = &c;        //Error p为常量,顶层const
19 
20 
21         const int *const p;//这个就相当于以上两种情况的混合体,p是常量,
22                           //所以不能把test2的地址赋给p;同时*p也是常量,所以*p的内容不可更改;
23         举例:
24         int test1 = 10;
25         int test2 = 20;
26         const int * const p = &test1;
27         p = &test2;        //Error,p是常量,所以不能把test2的地址赋给p;
28         *p = 30;        //Error,*p是常量,所以*p的内容不可更改;

 

posted @ 2015-10-08 22:13  蜗牛在奔跑  阅读(179)  评论(0编辑  收藏  举报