c++ const

来源:互联网 发布:阿国网络随笔123 编辑:程序博客网 时间:2024/06/05 00:41

1.常量指针与指针常量

常量指针是针对于普通指针而言,语义在于指向常量的指针;
定义:

const *<_name>;

常量指针解引用无法对引用值进行改变,但是可以改变指针自己的值;
example:

int tmp = 0, tmp2 = 1;
const int *p = &tmp;
p = &tmp2; // ok
*p = 1;//error

指针常量语义指针本身为常量;解引用可以改变指向的值,但是不能改变指针本身的值:
* const <_name>;

example:

int tmp = 0, tmp2 = 1;
int* const p = &tmp;
p = &tmp2; // error
*p = 1;//ok

typedef 与const

关于const有个地方特别容易出问题:
如下:

typedef int* int_p;
const int_p tmp;

这里的 tmp 到底是常量指针还是指针常量?一般的人会将typedef 直接替换那就理解为:const int_p tmp 与 const int* tmp相对应,其实这种理解是错的!!!
这里定义其实是一个指针常量;解释如下:
typedef的意义在于定义一个类型,也就是是int_p 并不是直接被int* 替换,const语义在于对于定义的类型为常量,所以这里语义上解释为指针常量,指针本身是常量。

0 0
原创粉丝点击