|
Static data members do not belong to class objects, but are shared by all class objects. You can understand it this way:
The static data member is independent of an object of the class, and its definition (allocating storage area) is not performed when the class object is defined, but independently.
The class definition itself does not allocate storage area, just introduce a type name (class type), so it must be defined outside the class definition, this is to allocate memory to static data members
class A
{
public:
static int i;
};
int main()
{
cout << A::i;
return 0;
}
If you write this, you will find that i does not exist
class A
{
public:
static int i;
};
int A::i =10;
int main()
{
cout << A::i;
return 0;
}
that's it
As for the initial value,
When it is pointed out in the class definition and when it is actually defined outside the class
Only one can be given. The routine above is given the initial value when it is actually defined.
Otherwise, how does the compiler know which one to use for initialization? |
|