例如,是
int const x = 3;
Run Code Online (Sandbox Code Playgroud)
有效代码?
如果是这样,它是否意味着相同
const int x = 3;
Run Code Online (Sandbox Code Playgroud)
?
Bri*_*ndy 105
它们都是有效的代码,它们都是等价的.对于指针类型,虽然它们都是有效代码但不等效.
声明2个常量的整数:
int const x1 = 3;
const int x2 = 3;
Run Code Online (Sandbox Code Playgroud)
声明一个指针,其数据无法通过指针进行更改:
const int *p = &someInt;
Run Code Online (Sandbox Code Playgroud)
声明一个无法更改为指向其他内容的指针:
int * const p = &someInt;
Run Code Online (Sandbox Code Playgroud)
T.E*_*.D. 32
是的,他们是一样的.C++中的规则基本上const适用于其左侧的类型.但是,有一个例外,如果你把它放在声明的最左边,它适用于该类型的第一部分.
例如,int const *你有一个指向常量整数的指针.在int * const你有一个指向整数的常量指针.你可以推断它指向指针,英语可能会让人感到困惑,但原理是一样的.
关于做另一个的优点的另一个讨论,请看我关于这个问题的问题.如果您很好奇为什么大多数人都会使用该例外,那么Stroustrup的这个FAQ条目可能会有所帮助.
Arc*_*hie 17
是的,这完全一样.但是,指针有所不同.我的意思是:
int a;
// these two are the same: pointed value mustn't be changed
// i.e. pointer to const value
const int * p1 = &a;
int const * p2 = &a;
// something else -- pointed value may be modified, but pointer cannot point
// anywhere else i.e. const pointer to value
int * const p3 = &a;
// ...and combination of the two above
// i.e. const pointer to const value
const int * const p4 = &a;
Run Code Online (Sandbox Code Playgroud)
来自"Effective C++"第21项
char *p = "data"; //non-const pointer, non-const data
const char *p = "data"; //non-const pointer, const data
char * const p = "data"; //const pointer, non-const data
const char * const p = "data"; //const pointer, const data
Run Code Online (Sandbox Code Playgroud)