C++ const int = int const?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3247285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
const int = int const?
提问by user383352
For example, is
例如,是
int const x = 3;
valid code?
有效代码?
If so, does it mean the same as
如果是这样,它的意思是否与
const int x = 3;
?
?
回答by Brian R. Bondy
They are both valid code and they are both equivalent. For a pointer type though they are both valid code but not equivalent.
它们都是有效的代码,它们都是等价的。对于指针类型,虽然它们都是有效代码但不等价。
Declares 2 ints which are constant:
声明 2 个常量:
int const x1 = 3;
const int x2 = 3;
Declares a pointer whose data cannot be changed through the pointer:
声明一个指针,其数据不能通过指针改变:
const int *p = &someInt;
Declares a pointer who cannot be changed to point to something else:
声明一个不能更改为指向其他内容的指针:
int * const p = &someInt;
回答by T.E.D.
Yes, they are the same. The rule in C++ is essentially that const
applies to the type to its left. However, there's an exception that if you put it on the extreme left of the declaration, it applies to the first part of the type.
是的,它们是一样的。C++ 中的规则本质上const
适用于其左侧的类型。然而,有一个例外,如果你把它放在声明的最左边,它适用于类型的第一部分。
For example in int const *
you have a pointer to a constant integer. In int * const
you have a constant pointer to an integer. You can extrapolate this to pointer to pointers, and the English may get confusing but the principle is the same.
例如,int const *
您有一个指向常量整数的指针。在int * const
你有一个指向整数的常量指针。您可以将其推断为指向指针的指针,英语可能会令人困惑,但原理是相同的。
For another dicussion on the merits of doing one over the other, see my questionon the subject. If you are curious why most folks use the exception, this FAQ entryof Stroustrup's may be helpful.
有关做一个比另一个的优点的另一次讨论,请参阅我关于该主题的问题。如果您对为什么大多数人使用异常感到好奇,Stroustrup 的这个 FAQ 条目可能会有所帮助。
回答by Archie
Yes, that is exactly the same. However, there is difference in pointers. I mean:
是的,这完全一样。但是,指针存在差异。我的意思是:
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;
回答by Yuan
From "Effective C++" Item 21
来自“有效的 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
回答by ttchong
It is the same in meaning and validity.
它在意义和有效性上是一样的。
As far as I know, const only get complex whenever it involves pointer.
据我所知, const 只有在涉及指针时才会变得复杂。
int const * x;
int * const x;
are different.
是不同的。
int const * x;
const int * x;
are same.
是一样的。