Static members can also be defined in a class, but static members are public to all objects. Static members are divided into static data members and static member functions.
1. Static data members
The way to define a static data member in a class is to precede the member with the keyword static.
The statement format that defines a static data member is as follows:
Class name
{
......
Static type descriptor member name;
......
};
A static data member is a shared member of all objects of a class. The space occupied by static data members is not allocated as objects are generated, and is not recycled as objects disappear. The operation of a static data member is different from that of a generic data member in a class, and static data members defined as private cannot be accessed by the outside world. Static data members can be accessed by functions that are licensed by any access permission.
Because static data members are shared by all objects of a class, and not from any particular object, therefore, the static data member of the class must be initialized, but its initialization cannot be done in the class's constructor, and its initialization statement should be written in the program's global zone and must indicate its data type and the class name to which it belongs. The initialization format is as follows:
Type class Name:: Variable name = value;
Static data members that are described in the public section of a class can be accessed directly outside of a class without using a member function, but must be used to indicate the class to which it belongs, and the access format is:
Class Name:: Static data member name
For static data members that are described in a non-public part of a class, they can only be accessed by a member function of the class, and the access method is exactly the same as accessing the normal data members in the class, but not outside the class.