#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 开发者_如何学Creference to `B::b'
undefined reference to `B::b'
undefined reference to `B::b'
Static variables need to be allocated outside the class. Add this line outside the class B:
int B::b;
Think of static variables as being declared with the extern
keyword. They still need to be allocated somewhere. This means the allocation should never be in the header file!
Because it is static, you also need to define storage for B::b
(in a class definition, all you have done is declared the variable).
You need to add:
int B::b;
You have to initialize your static member in the according .cpp file like int B::b = 0
精彩评论