A private static data member in Cpp .. can only be initialized when it is defined, but invalid initialization in the class?

Initialization in the header file causes the following error:

invalid in-class initialization of static data member of non-integral type 'bool [8]' 

if I try to initialize in .cpp, I get:

 'bool Ion::KeyboardInput::key [8]' is a static data member; it can only be initialized at its definition 

Here is the title:

 enum MYKEYS { KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_W, KEY_S, KEY_A, KEY_D }; class KeyboardInput { public: KeyboardInput(); ~KeyboardInput(); static void getKeysDown(ALLEGRO_EVENT ev); static void getKeysUp(ALLEGRO_EVENT ev); static bool getKey(int keyChoice); private: static bool key[8] = {false, false, false, false, false, false, false, false}; }; 
+4
source share
3 answers

The first error message tells you that initializing a static member variable in the header file is not correct. The second error message means that you tried to initialize the static member key in your constructor.

A static member variable of a class must be declared inside the class (without initialization) and then defined outside the class in the .cpp file (sort of like a global variable, except that the variable name has the class name included in it).

 bool KeyboardInput::key[8]; 

A variable definition may include an initializer. Since you initialized it for all false, the above definition in your .cpp file is sufficient.

A static member variable of a class is not too different from a global variable, except that it is limited to the class name and can only be protected for class members (with private ), immediate class subclasses (using protected ) or friends of the class.

+4
source

You must declare the statics in the .h file and assign values ​​to it in the .cpp file. Something like that,

_header.h

 class KeyBoardInput{ public: KeyboardInput(); .... private: static bool key[8]; }; 

_header.cpp

 \#include<"_header.h"> bool KeyBoardInput::key[8] = {false, false, false, false, false, false, false, false}; 

Apart from the cpp file, you cannot initialize a static variable anywhere ... This does not apply to a specific object. Therefore, you must initialize outside the class (in the cpp file) so that all objects can share it.

+3
source

Try the following:

 enum MYKEYS { KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_W, KEY_S, KEY_A, KEY_D }; class KeyboardInput { public: KeyboardInput(); ~KeyboardInput(); static void getKeysDown(ALLEGRO_EVENT ev); static void getKeysUp(ALLEGRO_EVENT ev); static bool getKey(int keyChoice); private: static bool key[8]; }; bool KeyboardInput::key = {false, false, false, false, false, false, false, false}; 

The last line should really be placed in the .cpp file, since all the "code" should be in the cpp file.

0
source

All Articles