views:

502

answers:

4

Hi,

I have a class and I want to have some bit masks with values 0,1,3,7,15,...

So essentially i want to declare an array of constant int's such as:

class A{

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

}

but the compiler will always complain.

I tried:

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

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

Any idea on how this can be done?

Thanks!

+2  A: 
enum Masks {A=0,B=1,c=3,d=5,e=7};
EvilTeach
The problem with this approach is that i want to be able to use it like an array. For example call a value mask[3] and get a specific mask.
Juan Besa
Ok. understood.you want to use litbs answer then, that's the way to do it.
EvilTeach
+9  A: 
class A {
    static const int masks[];
};

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

You may want to fixate the array within the class definition already, but you don't have to. The array will have a complete type at the point of definition (which is to keep within the .cpp file, not in the header) where it can deduce the size from the initializer.

Johannes Schaub - litb
+3  A: 
// in the .h file
class A {
  static int const masks[];
};

// in the .cpp file
int const A::masks[] = {0,1,3,5,7};
Mr Fooz
+2  A: 
  1. you can initialize variables only in the constructor or other methods.
  2. 'static' variables must be initialized out of the class definition.

You can do this:

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

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