1, static data member
In C + +, static data members of a class are identified by the static e.g:
Class MyClass
{
Private
static int Num;
Double A;
Long B;
......
}
When NUM is declared static, static data members have some features: no matter how many objects are created, there is only one copy of the static data member. That is, static data members belong to classes, not every object has a static data member, and all objects of the class share a static data member. For example, we create two MyClass objects with 2 A and B members, but there is only one shared num, and this num is stored in extra space, not part of the object.
Initialization of a static data member:
(1), the location of the initialization
We should initialize the method definition file instead of in the class declaration file (header file). This is because the class declaration is in the header, and the header file may be contained in multiple files, and if something goes wrong in the header file, multiple initialization statements will appear and the compiler will give an error.
(2) Initialize the method.
Indicates the data type and uses the qualified name (class name + scope resolution operator), but no longer requires the keyword static
such as: int myclass::num = 0;
Precautions:
1, you cannot initialize a static data member in a class declaration, because the class declaration simply describes how to allocate memory, but does not allocate memory, that is, the class declaration simply declares a data type (user-defined type), just like an int, We can use this type of class to define variables just like using basic built-in types such as int. Simply put, MyClass is like an int, which allocates memory only when the variable is defined.
2, you cannot use a constructor to initialize a static data member because it belongs to a class and not to a particular object of the class.
3, there is an out-of-class condition where a static data member is a const or enumerated type and can be initialized in a class declaration.
In general, static data members are shared among the objects of the class and belong to the class, not to the object belonging to the class.
Static members of C + + classes