![](/img/trans.png)
[英]How to initialize static const member that is array of another class, and use it?
[英]How to declare and initialize a static const array as a class member?
非常不言自明。 数组是整数类型,内容是已知且不变的,并且不允许使用C ++ 0x。 它还需要声明为指针。 我似乎无法找到有效的语法。
Class.hpp中的声明:
static const unsigned char* Msg;
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)
...等等。 我也尝试在构造函数中初始化,这当然不起作用,因为它是一个常量。 我要求的是不可能的吗?
// 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;
你是混合指针和数组。 如果你想要的是一个数组,那么使用一个数组:
struct test {
static int data[10]; // array, not pointer!
};
int test::data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
另一方面,如果你想要一个指针,最简单的解决方案是在定义成员的转换单元中编写一个辅助函数:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.