简体   繁体   中英

declare a array of const ints in C++

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!

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.

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

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

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.
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, .... };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM