例如,is
int const x = 3;有效代码?
如果是这样的话,这是否意味着
const int x = 3;发布于 2010-07-14 22:48:22
它们都是有效的代码,并且它们都是等价的。对于指针类型,虽然它们都是有效的代码,但不是等价的。
声明2个常量整型数:
int const x1 = 3;
const int x2 = 3;声明一个指针,该指针的数据不能通过指针更改:
const int *p = &someInt;声明一个指针,该指针不能更改为指向其他对象:
int * const p = &someInt;发布于 2010-07-14 22:57:24
是的,它们是一样的。C++中的规则本质上是将const应用于其左侧的类型。但是,有一个例外,如果您将它放在声明的最左边,它将应用于类型的第一部分。
例如,在int const *中,您有一个指向常量整数的指针。在int * const中,你有一个指向整数的常量指针。你可以把它外推到指向指针的指针上,英语可能会让人感到困惑,但原理是一样的。
关于做一件事比另一件事的优点的另一讨论,请参阅该主题的my question。如果你很好奇为什么大多数人都使用这个例外,那么Stroustrup的this FAQ entry可能会有所帮助。
发布于 2010-07-14 22:51:28
是的,这是完全一样的。但是,指针不同。我的意思是:
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;https://stackoverflow.com/questions/3247285
复制相似问题