What is the problem with this code?

#include<stdio.h> class A { public: int a;}; class B: public A { public: static int b; B(){ b++; printf("B:%d\n",b); } }; int main() { A* a1 = new B[100]; A* a2 = new B(); return 0; } 

Error:

 In function `main': undefined reference to `B::b' undefined reference to `B::b' undefined reference to `B::b' undefined reference to `B::b' 
+4
source share
3 answers

Static variables must be allocated outside the class. Add this line outside of class B:

 int B::b; 

Think of static variables declared using the extern keyword. They still need to be allocated somewhere. This means that the distribution should never be in the header file!

+16
source

Since it is static, you also need to define a repository for B::b (in the class definition, everything you did is declared a variable).

You need to add:

 int B::b; 
+3
source

You must initialize your static member in the appropriate .cpp file, such as int B :: b = 0

0
source

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


All Articles