One. Static data members
The declaration of a data member in the class body is preceded by the static keyword, which becomes a data member of that class. As with other data members, static data members also adhere to public/protected/private access rules. At the same time, static members also have the following characteristics:
1. Definition of a static data member.
A static data member is actually a global variable in a class domain. Therefore, the definition of a static data member should not be placed in the header file. Static data members are not subject to private and protected access restrictions when they are initialized.
Note: Do not attempt to define static data members in the header file. In most cases, doing so will cause a duplicate definition of such an error.
2. Static data members are shared by all objects of the class, including objects of the class's derived classes. That is, the derived class object and the base class object share the static data members of the base class.
1#include <iostream>2 using namespacestd;3 4 class Base{ 5 Public: 6 Static int_num;7 }; 8 9 int Base:: _num =0;Ten One classDerived: Public Base A { - }; - the intMain () - { - BaseA; -derived B; +a._num++; -cout <<"base class static data _num is:"<< A._num <<Endl; +b._num++; Acout <<"derived class static data _num is:"<< B._num <<Endl; at return 0;
[Email protected] test]$./a. Outbaseclassstaticis1 classstaticis2
The result of the execution of the above program shows that the objects of the derived class and the base class share a static data member.
3. A static data member can be an optional parameter to a member function, while a normal member function is not possible.
4. The type of a static data member can be the type of the owning class, but ordinary data members cannot.
1 class base{2 public:3 static base _object1;//correct, static data member 4 base _object2; Error 5 };
Reference
Http://www.jb51.net/article/72387.htm
Http://www.jb51.net/article/41775.htm
C + +: static data members