C ++ static int in class - compile-time error

I want to have a simple class that I can call to get a unique number while the program is running. I can do the following with dynamic allocation, and then just deletewhen it is not needed, but I still wanted to get a static. Oddly enough, the code below (which would seem to be straightforward) causes some strange errors (attached below).

Any ideas what is going on? is it the wrong use of static?

class Id_gen {
    private:
 //adding static here stops the code from compiling:
 static int curr_id;

    public:

 Id_gen() {curr_id = 1; cout<<"debug:constructed"; }
 int get_id() {curr_id++; return curr_id; };
};

int main () {


    Id_gen bGen;
    cout << bGen.get_id() <<endl;

return 0;    
}

g ++ (linux 64) works:

c++2.cpp:(.text._ZN6Id_genC1Ev[Id_gen::Id_gen()]+0xe): undefined reference to `Id_gen::curr_id'
/tmp/cc766N6p.o: In function `Id_gen::get_id()':
c++2.cpp:(.text._ZN6Id_gen6get_idEv[Id_gen::get_id()]+0xa): undefined reference to `Id_gen::curr_id'
c++2.cpp:(.text._ZN6Id_gen6get_idEv[Id_gen::get_id()]+0x13): undefined reference to `Id_gen::curr_id'
c++2.cpp:(.text._ZN6Id_gen6get_idEv[Id_gen::get_id()]+0x19): undefined reference to `Id_gen::curr_id'
+3
source share
5 answers

Add initialization / definition of the static member as:

int Id_gen::curr_id = 0;

after class definition.

EDIT: @sbi: , .

+3

static :

int Id_gen::curr_id;
+2

( cpp):

int Id_Gen::curr_id = 0; // Initial value
0

, :

int Id_Gen::curr_id = 0;
0

, :

int Id_Gen::curr_id;

, get_id() . Id_Gen::get_id(), . , Id_Gen, reset id.

0

Source: https://habr.com/ru/post/1744897/


All Articles