C++ 如何将静态常量数组声明和初始化为类成员?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11367141/
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
How to declare and initialize a static const array as a class member?
提问by ACK_stoverflow
Pretty self-explanatory. The array is of an integral type, the contents are known and unchanging, and C++0x isn't allowed. It also needs to be declared as a pointer. I just can't seem to find a syntax that works.
不言自明。数组为整型,内容已知且不变,不允许使用C++0x。它还需要声明为指针。我似乎无法找到有效的语法。
The declaration in Class.hpp:
Class.hpp 中的声明:
static const unsigned char* Msg;
Stuff in Class.cpp is really what I've tinkered with:
Class.cpp 中的东西确实是我修改过的:
const unsigned char Class::Msg[2] = {0x00, 0x01}; // (type mismatch)
const unsigned char* Class::Msg = new unsigned char[]{0x00, 0x01}; // (no C++0x)
...etc. I've also tried initializing inside the constructor, which of course doesn't work because it's a constant. Is what I'm asking for impossible?
...等等。我也试过在构造函数内部初始化,这当然不起作用,因为它是一个常量。我的要求是不可能的吗?
回答by Michael Burr
// in foo.h
class Foo {
static const unsigned char* Msg;
};
// in foo.cpp
static const unsigned char Foo_Msg_data[] = {0x00,0x01};
const unsigned char* Foo::Msg = Foo_Msg_data;
回答by David Rodríguez - dribeas
You are mixing pointers and arrays. If what you want is an array, then use an array:
您正在混合指针和数组。如果你想要的是一个数组,那么使用一个数组:
struct test {
static int data[10]; // array, not pointer!
};
int test::data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
If on the other hand you want a pointer, the simplest solution is to write a helper function in the translation unit that defines the member:
另一方面,如果您想要一个指针,最简单的解决方案是在定义成员的翻译单元中编写一个辅助函数:
struct test {
static int *data;
};
// cpp
static int* generate_data() { // static here is "internal linkage"
int * p = new int[10];
for ( int i = 0; i < 10; ++i ) p[i] = 10*i;
return p;
}
int *test::data = generate_data();