C++ 在头文件中初始化常量静态数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2117313/
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
Initializing Constant Static Array In Header File
提问by user174084
I have just found out that the following is not valid.
我刚刚发现以下内容无效。
//Header File
class test
{
const static char array[] = { '1', '2', '3' };
};
Where is the best place to initialize this?
初始化它的最佳位置在哪里?
回答by Mike Seymour
The best place would be in a source file
最好的地方是在源文件中
// Header file
class test
{
const static char array[];
};
// Source file
const char test::array[] = {'1','2','3'};
You can initialize integer types in the class declaration like you tried to do; all other types have to be initialized outside the class declaration, and only once.
您可以像尝试那样在类声明中初始化整数类型;所有其他类型都必须在类声明之外初始化,并且只能初始化一次。
回答by JKD
You can always do the following:
您始终可以执行以下操作:
class test {
static const char array(int index) {
static const char a[] = {'1','2','3'};
return a[index];
}
};
A couple nice things about this paradigm:
关于这个范式的一些好处:
- No need for a cpp file
- You can do range checking if you want to
- You avoid having to worry about the static initialization fiasco
- 不需要cpp文件
- 如果您愿意,您可以进行范围检查
- 您不必担心静态初始化失败
回答by peterchen
//Header File
class test
{
const static char array[];
};
// .cpp
const char test::array[] = { '1', '2', '3' };
回答by lz96
Now, in C++17, you can use inline variable
现在,在 C++17 中,您可以使用内联变量
A simple static data member(N4424):
struct WithStaticDataMember { // This is a definition, no out-of-line definition is required. static inline constexpr const char *kFoo = "foo bar"? }?
一个简单的静态数据成员(N4424):
struct WithStaticDataMember { // This is a definition, no out-of-line definition is required. static inline constexpr const char *kFoo = "foo bar"? }?
In your example:
在你的例子中:
//Header File
class test
{
inline constexpr static char array[] = { '1', '2', '3' };
};
should just work
应该工作
回答by Jim Hunziker
This is kind of an abuse of the system, but if you REALLY want to define it in the header file (and you don't have C++17), you can do this. It won't be a static member, but it will be a constant that only takes up storage per compilation unit (rather than per class instance):
这是对系统的一种滥用,但如果您真的想在头文件中定义它(并且您没有 C++17),您可以这样做。它不会是一个静态成员,但它将是一个常量,只占用每个编译单元(而不是每个类实例)的存储空间:
(Put all of this code in the header file.)
(将所有这些代码放在头文件中。)
namespace {
const char test_init_array[] = {'1', '2', '3'};
}
class test {
public:
const char * const array;
test() : array(test_init_array) {}
};