如何将静态 const 数组声明和初始化为类成员

How to declare and initialize a static const array as a class member?

本文关键字:初始化 成员 声明 数组 静态 const      更新时间:2023-10-16

不言自明。 数组是整数类型,内容已知且不变,不允许使用 C++0x。 它还需要声明为指针。 我似乎找不到有效的语法。

Class.hpp 中的声明:

static const unsigned char* Msg;

课堂上的东西.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();