我在为 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
之前或之后,这是它所修改的。
- 那么,在第 4 行,编译器如何确定
const
正在修改*
(指针)而不是int
? - 编译器遵循什么规则来决定
const
适用于哪个事物? *
是否遵循相同的规则?
最佳答案
假设你总是把 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/