我从这个答案中知道指针const int** z
应该被读取为
变量z是[指向[指向
const int
对象的指针]]的指针。
在我看来,这意味着如果z=&y
那么y
应该是指向const int
对象的指针。但是,下面的代码也可以编译:
int x=0;
int const* y=&x;
const int** z=&y;
为什么int const*
对象,即const
指针指向int
,而不是指向const int
的指针可以成为z
的指向对象?
您误解了const所指的内容。const总是指向它左边的元素——除非它本身是最左边的元素,它指向右边的元素。
这意味着int const *
是一个指向const int类型的指针,而不是你认为的指向int类型的const指针。要得到它,你必须写int * const
int const *
和const int *
是两种完全相同的书写方式:指向const int类型的指针。
const int *
:指向const类型的int型指针。int const *
:指向const int.int * const
: const指针指向int.const int * const
:指向const的int指针。int const * const
: const指针指向const int.
注意1/2是相同的,4/5是相同的。1和4被称为"西部构造";由于const在西面/左边,而2和5被称为"东面const"。
为什么是
int const
*对象,即const
指针指向int
号
int const *
和const int *
是同一类型。
人们有时更喜欢写int const *
,因为它从右向左读为"指向const int">,而const int *
实际上读为"指向int (const)">。
指向int
的const
指针是int * const
。
试一试:
int a = 42;
const int * y = &a;
int const * z = &a;
*y = 24; // compile error assigning to const
*z = 24; // compile error assigning to const
int b = 0;
y = &b;
z = &b; // re-pointing non-const pointers is fine
*z = 1; // still a compile error
int * const x = &a;
*x = 24; // fine, assigning via pointer to non-const
x = &b; // error reassigning a const pointer