const int *p = &a;
int const *p = &a;
int *const p = &a;
const int *const p = &a;
const int *p = &a;
int const *p = &a;
int *const p = &a;
const int *const p = &a;
一句话,从右往左读。因为中英文在这里语序相反,所以比较麻烦。
c
const int *p = &a; // p指针指向const int (p is a pointer to const int) int const *p = &a; // p指针指向const int (p is a pointer to const int) int *const p = &a; // p为const指针,指向int (p is a const pointer to int) const int *const p = &a; // p为const指针,指向const int (p is a const pointer to const int)
此外还有
int *&p; // p是引用,其被引用对象为指向int的指针 (p is a reference to pointer to int)
int const *& p; // p是引用,其被引用对象是指向int的指针常量
甚至
int * const * const * * p; // p是指向指向指向指向指向整数的指针常量的指针常量的指针的指针
// (p is a pointer to a pointer to a const pointer to a const pointer to int)
当然这样就没啥用处了 :P
const
就是代表不能修改值,对于 int *p
的定义,有两种可能的修改,一个是p
指向的内存的值,一个是p
的值;
要记住很简单,const
离谁近,就谁不能修改;const int *p
,离*
比离p近,所以*
不能修改,即内存的值不可修改;int * const p
;已经跨过*
,离p
近了,p
不可修改,即p
这个指向一个地址了,就不能再想指向另一个地址了;
3 回答1.1k 阅读✓ 已解决
1 回答976 阅读✓ 已解决
4 回答765 阅读
1 回答844 阅读
1 回答876 阅读
1 回答641 阅读
1 回答752 阅读
const int*
和int const*
是同一种类型,指针指向的是一个const int
,也就是说不能通过指针p
来修改a
的值。int* const p=&a
中const
直接修饰p
,即指针本身是const
,它的值已经初始化为&a
,不能修改,但是可以通过p
来修改a
的值,如*p=0
;const int* const
则是上面二者的叠加,一方面指针p
本身是const
,其值初始化为&a
不能修改,另一方面指针p
所指向的数据类型是const int
,即不能通过p
来修改a
的值。