在C++中声明一个常量整数数组

14

我有一个类,想要使用值为0、1、3、7、15等的位掩码。

因此,我想声明一个常量 int 数组,例如:

class A{

const int masks[] = {0,1,3,5,7,....}

}

但是编译器总是会抱怨。

我尝试过:

static const int masks[] = {0,1...}

static const int masks[9]; // then initializing inside the constructor

有什么办法可以做到这一点吗?

谢谢!

5个回答

29
class A {
    static const int masks[];
};

const int A::masks[] = { 1, 2, 3, 4, ... };

你可能想在类定义中就固定数组大小,但这并非必须。在定义数组的地方(应该放在.cpp文件中,而不是头文件中),它已经有了完整的类型,并且可以通过初始化值推断大小。


9
// in the .h file
class A {
  static int const masks[];
};

// in the .cpp file
int const A::masks[] = {0,1,3,5,7};

由于在更复杂的情况下,追加而不是前置const也可以起作用,因此我更喜欢这个解决方案。 - Jacques de Hooge

2
由于无法直接初始化私有成员变量,您需要调用一个方法来进行初始化。 对于常量和静态数据成员,我通常使用成员初始化列表进行初始化。
如果您不知道成员初始化列表是什么,那就来看看这个代码吧:
    class foo
{
int const b[2];
int a;

foo():    b{2,3}, a(5) //initializes Data Member
{
//Other Code
}

}

此外,GCC还有一个很酷的扩展功能:
const int a[] = { [0] = 1, [5] = 5 }; //  initializes element 0 to 1, and element 5 to 5. Every other elements to 0.

2
enum Masks {A=0,B=1,c=3,d=5,e=7};

这种方法的问题在于我想像使用数组一样使用它。例如,调用值mask[3]并获取特定的掩码。 - Juan Besa
好的,明白。如果你想使用litbs的答案,那么就是这样做。 - EvilTeach

2
  1. 你只能在构造函数或其他方法中初始化变量。
  2. “static”变量必须在类定义之外初始化。

你可以这样做:

class A {
    static const int masks[];
};

const int A::masks[] = { 1, 2, 3, 4, .... };

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接