指向指向const对象的指针的合法定义是什么?



我从这个答案中知道指针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是最左边的元素,添加一个"在它阅读之前。例:
  1. const int *:指向const类型的int型指针。
  2. int const *:指向const int.
  3. int * const: const指针指向int.
  4. const int * const:指向const的int指针。
  5. 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)">

指向intconst指针是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

最新更新