0

I'm trying to initialize an array in a class' header file:

class C {
    private:
        static float p[26] = {
            0.09, 0.02, 0.02, 0.04, 0.12, 0.02, 0.03, 
            0.02, 0.09, 0.01, 0.01, 0.04, 0.02, 0.06, 
            0.08, 0.02, 0.01, 0.06, 0.04, 0.06, 0.04, 
            0.02, 0.02, 0.01, 0.02, 0.01
        };
...

I'm getting the following error(s) from g++:

C.h:15:33: error: a brace-enclosed initializer is not allowed here before ‘{’ token

C.h:20:9: sorry, unimplemented: non-static data member initializers

C.h:20:9: error: ‘constexpr’ needed for in-class initialization of static data member ‘p’ of non-integral type

I'm forced to use c++0x; how can I define this array without doing p[0], p[1], etc.?

Community
  • 1
  • 1
sheppardzw
  • 924
  • 1
  • 7
  • 15

2 Answers2

3

You can declare the static member variable of the class in a header file using:

class C {
   private:
      static float p[26];
};

You can define it in a .cpp file using:

float C::p[26] = {
            0.09, 0.02, 0.02, 0.04, 0.12, 0.02, 0.03, 
            0.02, 0.09, 0.01, 0.01, 0.04, 0.02, 0.06, 
            0.08, 0.02, 0.01, 0.06, 0.04, 0.06, 0.04, 
            0.02, 0.02, 0.01, 0.02, 0.01
        };
R Sahu
  • 204,454
  • 14
  • 159
  • 270
2

Unfortunately, you cannot initialize your static members in the class declaration (exceptions are made for const integral and const enum types).

You should define (and initialize) your static member in one separate compilation unit (usually it's done in the *.cpp file corresponding to your class).

So, you'll have:

// code in C.h
class C {
static float p[]; // declaration of C::p
}

and

// code in C.cpp
float C::p[] = { /* put your numbers here */ }; // definition of C::p

If the terms "declaration" and "definition" are confusing to you, read the answers to this question.

Community
  • 1
  • 1
nicebyte
  • 1,498
  • 11
  • 21