【问题标题】:Is "pointer to const int" same as " const int* "“指向 const int 的指针”是否与“const int*”相同
【发布时间】:2021-05-10 16:26:18
【问题描述】:
我正在阅读有关指针的内容,但其中一部分感到困惑。给出的代码如下:
int i=0;
const int ci = i;
auto *p = &ci;`
现在的问题是p 的类型是什么?我认为p 将是一个指向 const int 的指针。它是否正确?如果是,这是否等于 const int*?指向const int 的指针是否与const int* 相同?
【问题讨论】:
标签:
c++
pointers
constants
auto
【解决方案1】:
在 C++ 中,const 关键字通常适用于其左侧的类型部分。
所以int const* 是一个指向常量整数的指针,int*const 是一个指向非常数整数的常量指针。
您示例中p 的类型是int const*。
将const 放在右边的习惯称为east const。
现在“const应用于左边”有一个例外;当左边没有什么都没有时,它适用于右边。这个令人困惑的异常意味着const int* 是int const*。但是using X=int*; const X 变成了int*const。
将const 放在左边的习惯,以及由此产生的混乱,被称为west const。
简而言之,答案是肯定的,除非你添加别名。
【解决方案2】:
我认为 p 将是一个指向 const int 的指针。
是的,p 就是这样。
如果是,这是否等于const int*?
是的:const int* p; 正是您将p 定义为指向const int 的指针。
以防万一您想知道,您可以定义/初始化一个指向(非常量)int 的 const 指针,如下所示:
int* const cp = &i;
而且,对于指向const int 的const 指针,您需要两次const 限定符:
const int* const cp = &ci;