2009-05-30 69 views
13

我有一个类,我想和值0,1,3,7,15一些位掩码的阵列,...声明在C++中const的整数

所以基本上我要声明一个数组例如:

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 

如何可以做到这一点任何想法?

谢谢!

回答

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

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

您可能希望已经固定类定义中的数组,但你不必。该数组在定义时会有一个完整的类型(它保存在.cpp文件中,而不是头文件中),它可以从初始化程序中推断出它的大小。

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

这种方法的问题是,我希望能够使用它像一个数组。例如调用一个值掩码[3]并获得一个特定的掩码。 – 2009-05-30 01:53:20

+0

好的。了解。 你想用litbs答案,那就是这样做的方法。 – EvilTeach 2009-05-30 02:21:01

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

// in the .cpp file 
int const A::masks[] = {0,1,3,5,7}; 
2
  1. 你只能在构造函数或其他方法初始化变量。
  2. '静态'变量必须从类定义中初始化。

你可以这样做:

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

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

好,这是因为你不能没有调用一个方法初始化一个私有成员。 我总是使用成员初始化列表为const和静态数据成员这样做。

如果你不知道什么成员初始化列表是,他们正是你想要的。

看看这段代码:

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. 
相关问题