简体   繁体   English

在头文件中声明并初始化常量

[英]Declare and initialize constant in header file

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 .h files for use with libraries or other instances where you cannot access the implementation file. 但是,必须有一种方法可以将其放入.h文件中,以供无法访问实现文件的库或其他实例使用。

For example, I'm trying to add an NSString constant to a .h file in an Xcode project like so: 例如,我试图将NSString常量添加到Xcode项目中的.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. myString ,指示未正确实例化它。 How does one declare compile-time constants in a C++ or Objecitve-C header file? 如何在C ++或Objecitve-C头文件中声明编译时常量?

In C++, const objects have internal linkage unless explicitly declared extern , so there is no problem with putting a definition into a header file such as: 在C ++中,除非显式声明extern ,否则const对象具有内部链接,因此将定义放入头文件中没有问题,例如:

const int myInt = 55;

With this definition and first declaration, myInt can be used as an integer constant expression such as for array bounds and the like. 通过此定义和第一个声明, myInt可以用作整数常量表达式,例如用于数组边界等。

I can't answer for Objective C. 我无法回答目标C。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM