gpt4 book ai didi

c++ - 理解 "const"在声明中的位置

转载 作者:IT老高 更新时间:2023-10-28 23:17:10 27 4
gpt4 key购买 nike

我在为 C 和 C++ 语言的声明中使用 const 的方式找到直观的模式时遇到了麻烦。以下是一些示例:

const int a;    //Const integer
int const a; //Const integer
const int * a; //Pointer to constant integer
int * const a; //Const pointer to an integer
int const * a const; //Const pointer to a const integer

在第 1 行和第 2 行中,似乎 const 可以出现在 int 之前或之后,这是它所修改的。

  1. 那么,在第 4 行,编译器如何确定 const 正在修改 *(指针)而不是 int
  2. 编译器遵循什么规则来决定 const 适用于哪个事物?
  3. * 是否遵循相同的规则?

最佳答案

假设你总是把 const 放在类型的 right 上,你可以从右到左把变量声明读成一句话:

int const x;        // x is a constant int
int *const x; // x is a constant pointer to an int
int const *x; // x is a pointer to a constant int
int const *const x; // x is a constant pointer to a constant int

如果您将 const 放在类型的左侧,这仍然有效,但需要更多的脑力劳动。请注意,这同样适用于指向指针的指针(和更高阶的结构):

int *const *const x; // x is a constant pointer to a constant pointer to an int

关于c++ - 理解 "const"在声明中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6590820/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com