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
,这就是它所修改的内容.
const
修改*
(指针)而不是int
?const
适用的内容?*
吗?假设您始终位于类型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)
编译器通常从右到左读取类型,因此:
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可能是个好主意.