Here is my code -
#include <iostream>
#include <conio.h>
using namespace std;
class Base
{
public:
int a;
};
//int Base::a = 5;
class Derived : public Base
{
public:
int static a;
};
int main()
{
Derived d;
cout<<d.a;
开发者_开发知识库 getch();
return 0;
}
I get a linker error here. But when I do it the other way round -
class Base
{
public:
int static a;
};
int Base::a = 5;
class Derived : public Base
{
public:
int a;
};
I get no error. Can someone please explain what is happening here.
All static members have to be explicitly defined/initialized outside the class.
In the second example you do this correctly (int Base::a=5), but in the first example you don't do this for Derived::a, adding the following line to the first example should solve it:
int Derived::a = 5;
You need to actually define static members. The same way as you do
int Base::a = 5
in the second case you should have done
int Derived::a = 5;
in the first case.
There are two questions here. The first is why do you get the linker error in the first example? Well, you get a linker error in the first example because you have not defined/initialized the static member of class B.
The second question is why does the compiler not complain of multiple declarations? The compiler does not complain of multiple declarations because as far as it is concerned, the two variables are in different scopes and their mangled names will be different anyway. This has got nothing to do with one of the variables being static. In fact, static members are not even inherited. SO, the following code snippet without static variables is also correct:
class B {
public:
int a;
};
class C: public B {
public:
int a;
};
精彩评论