简体   繁体   English

为什么我们不能将低+顶级const指针定义为指向int的指针?

[英]Why can we not define a low + top-level const pointer to a pointer to int?

  1. Define int and pointer to int: 定义int和指向int的指针:

    int i = 22, *p = &i;

  2. Define pointer that is low level and top-level const: 定义低级和顶级const的指针:

    const int *const cp = p;

    (2) is alright - const point with no permission to change the value (of i) (2)没关系 - const点,无权改变(i)的值

  3. Definie a pointer to a pointer that is low+top-level const: 定义一个指向低级和顶层const指针的指针:

    const int **const cp_2_p = &p;

    (3) isn't alright, why? (3)不好,为什么?

    error C2440: 'initializing' : cannot convert from 'int **' to 'const int **const

I'd expect to be able to define a pointer to a pointer to int where I cannot change the address it points to nor the address the pointer it points to, points to. 我希望能够定义一个指向int的指针,在那里我不能改变它指向的地址,也不能指向指向它的指针的地址,指向。

In general, const applies to the item to its left. 通常, const适用于其左侧的项目。 The exception of const T is present for historical reasons, and is the conventional alternative to T const . 由于历史原因,存在const T例外,它是T const的常规替代方案。

cp is declared as a constant pointer to a constant int . cp被声明为常量int常量指针。

cp_2_p is declared as a constant pointer to a non-constant pointer to a constant int. cp_2_p被声明为指向常量int的非常量指针的常量指针。

You would need to declare cp_2_p like this for the types to be compatible: 您需要像这样声明cp_2_p才能使类型兼容:

const int *const *const cp_2_p

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM