理解"const"在声明中的位置

Ada*_*m S 12 c c++ syntax constants

我很难找到一种直观的模式,用于在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
Run Code Online (Sandbox Code Playgroud)

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

  1. 那么,在第4行,编译器如何决定const修改*(指针)而不是int
  2. 编译器遵循什么规则来决定const适用的内容?
  3. 它遵循相同的规则*吗?

Mic*_*val 7

假设您始终位于类型const右侧,您可以从右到左读取变量声明作为句子:

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
Run Code Online (Sandbox Code Playgroud)

如果你放在const一个类型的左边,这仍然有效,但需要更多的心理努力.请注意,这与指针指针(以及更高阶的构造)一样有效:

int *const *const x; // x is a constant pointer to a constant pointer to an int
Run Code Online (Sandbox Code Playgroud)


Mic*_*yan 5

编译器通常从右到左读取类型,因此:

T const& const
Run Code Online (Sandbox Code Playgroud)

将被理解为:

 const (a constant)
 & (to a reference)
 const (to a constant)
 T (of type T)
Run Code Online (Sandbox Code Playgroud)

所以,基本上关键字"const"会修改它之前的所有内容.但是,在首先出现"const"的情况下有一个例外,在这种情况下,它直接修改项目的右边:

const T& const
Run Code Online (Sandbox Code Playgroud)

以上内容如下:

const (a constant)
& (to a reference)
const T (to a constant of type T)
Run Code Online (Sandbox Code Playgroud)

以上等同于T const&const.

虽然编译器就是这样做的,但我真的只是建议记住"T","const T","const T&","const T*","const T&const","const T*const"," T&const"和"T*const".您很少会遇到"const"的任何其他变体,当您这样做时,使用typedef可能是个好主意.

  • 我相信没有"常量参考"这样的东西(换句话说,它们总是不变的).所以`T&const`在语义上是不正确的.VC++ 2010发出警告并忽略了`const`.只是提醒.:) (5认同)
  • -1表示不好的例子.你应该在这里使用指针,而不是引用. (2认同)