C++ 混合外部和常量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2190919/
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
Mixing extern and const
提问by legends2k
Can I mix extern and const, as extern const? If yes, does the constqualifier impose it's reign only within the scope it's declared in or should it exactly match the declaration of the translational unit it's declared in? I.e. can I declare say extern const int i;
even when the actual iis not a const and vice versa?
我可以混合 extern 和 const,作为extern const吗?如果是,const限定符是否仅在它声明的范围内强加它的统治,或者它是否应该与它声明的翻译单元的声明完全匹配?即,extern const int i;
即使实际i不是常量,我也可以声明 say ,反之亦然?
采纳答案by edgar.holleis
- Yes, you can use them together.
- And yes, it should exactly match the declaration in the translation unit it's actually declared in. Unless of course you are participating in the Underhanded C Programming Contest:-)
- 是的,您可以同时使用它们。
- 是的,它应该与它实际声明的翻译单元中的声明完全匹配。当然,除非您参加了Underhanded C Programming Contest:-)
The usual pattern is:
通常的模式是:
- file.h:
extern const int a_global_var;
- file.c:
#include "file.h"
const int a_global_var = /* some const expression */;
- 文件.h:
extern const int a_global_var;
- 文件.c:
#include "file.h"
const int a_global_var = /* some const expression */;
Edit: Incorporated legends2k's comment. Thanks.
编辑:合并legends2k的评论。谢谢。
回答by John Knoeller
You can use them together. But you need to be consistent on your use of const because when C++ does name decoration, const is included in the type information that is used to decorate the symbol names. so extern const int i
will refer to a different variable than extern int i
你可以一起使用它们。但是您需要在使用 const 时保持一致,因为当 C++ 进行名称修饰时,const 包含在用于修饰符号名称的类型信息中。soextern const int i
将引用不同的变量extern int i
Unless you use extern "C" {}. C name decoration doesn't pay attention to const.
除非您使用 extern "C" {}。C名称修饰不注意const。
回答by Jon Cage
You can use them together and you can do all sorts of things which ignore the const keyword, because that's all it is; a keyword. It tells the compiler that you won't be changing a variable which in turn allows the compiler to do some useful optomisations and stops you from changing things you didn't mean to.
你可以一起使用它们,你可以做各种忽略 const 关键字的事情,因为仅此而已;一个关键字。它告诉编译器你不会改变一个变量,这反过来又允许编译器做一些有用的优化并阻止你改变你不想要的东西。
Possibility.com has a decent articlewith some more background.
Possibility.com 有一篇不错的文章,有更多背景知识。
回答by Dimitri C.
Yes, you can use them together.
是的,您可以同时使用它们。
If you declare "extern const int i", then i is const over its full scope. It is impossible to redefine it as non-const. Of course you can bypass the const flag by casting it away (using const_cast).
如果您声明“extern const int i”,则 i 在其整个范围内都是 const。不可能将其重新定义为非常量。当然,您可以通过将其丢弃(使用 const_cast)来绕过 const 标志。