Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

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

// in the .cpp file
int const A::masks[] = {0,1,3,5,7};
enum Masks {A=0,B=1,c=3,d=5,e=7};
  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, .... };

Well, This is because you can't initialize a private member without calling a method. I always use Member Initialization Lists to do so for const and static data members.

If you don't know what Member Initializer Lists are ,They are just what you want.

Look at this code:

    class foo
{
int const b[2];
int a;

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

}

Also GCC has this cool extension:

const int a[] = { [0] = 1, [5] = 5 }; //  initializes element 0 to 1, and element 5 to 5. Every other elements to 0.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top