C++ 在头文件中声明和初始化常量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11194095/
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
Declare and initialize constant in header file
提问by Patrick Perini
I'm well versed in the typical paradigm of:
我精通以下典型范式:
//.h
extern const int myInt;
//.c, .m, .cpp, what have you
const int myInt = 55;
But there's got to be a way to put that into .hfiles for use with libraries or other instances where you cannot access the implementation file.
但是必须有一种方法将其放入.h文件中,以便与库或其他无法访问实现文件的实例一起使用。
For example, I'm trying to add an NSStringconstant to a .hfile in an Xcode project like so:
例如,我正在尝试向Xcode 项目中NSString的.h文件添加一个常量,如下所示:
static NSString *const myString = @"my_string";
however, when I attempt to use myString, I get the error
但是,当我尝试使用时myString,出现错误
Initializer element is not a compile-time constant
初始化元素不是编译时常量
on myString, indicating that it is not being properly instantiated. How does one declare compile-time constants in a C++ or Objecitve-C header file?
on myString,表明它没有被正确实例化。如何在 C++ 或 Objecitve-C 头文件中声明编译时常量?
回答by CB Bailey
In C++, constobjects have internal linkage unless explicitly declared extern, so there is no problem with putting a definition into a header file such as:
在 C++ 中,const除非明确声明extern,否则对象具有内部链接,因此将定义放入头文件中没有问题,例如:
const int myInt = 55;
With this definition and first declaration, myIntcan be used as an integer constant expression such as for array bounds and the like.
有了这个定义和第一个声明,myInt就可以用作整数常量表达式,例如用于数组边界等。
I can't answer for Objective C.
我无法回答目标 C。

