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.?

3
  • 2
    Make it constexpr or initialize it outside the class declaration. Commented Jan 30, 2015 at 2:43
  • @user657267 when I initialize it in the class constructor I get: "error: assigning to an array from an initializer list" Commented Jan 30, 2015 at 2:55
  • outside the class declaration. doesn't mean inside a constructor, please search on how to initialize static members. Commented Jan 30, 2015 at 2:56

2 Answers 2

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
        };
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.