Static member variables are stored in the data segment and are generated at compile time, with the following characteristics:
A static member variable is actually a global variable in a class domain, and its initialization should also be the same as a global variable, no longer initialized in the header file, as in the case of a global variable initialization, where static member variables are not subject to access qualifier qualification
Test.cpp:class a{static int _num;}; int a::_num = 0;//initialization succeeded
Static member variables are shared by all member variables within the class, and are also shared by all member variables of the derived class
Class B:p ublic a{};int Main () {A a;a._num++; B b;b._num++;cout << "b._num:" << b._num << endl;cout << "a._num:" << a._num << endl;r Eturn 0;}
Static member variables are constant and can be optional for member classes, and ordinary member variables are not constant, so they cannot be used as optional parameters for member functions
Class B:p ublic a{public:void fun (int a = _num)//correct {}void fun1 (int a = num)//error {}private:int num;};
A static member variable can be declared as the owning class type, the same member variable cannot be declared as the owning class type, and can only be declared as a reference and pointer to the owning class type (this is the node)
Class B:p ublic a{public:void fun (int a = _num)//correct {}void fun1 (int a = num)//error {}private:int num;static b _bclass;//correct b _b 1class;//error b* _bclassptr;//correct, for a pointer b &_b2class;//error, for a reference};
Because static member variable definitions are not within the class, the values of the static data members can be legitimately changed in the const member function.
class a{public:static int _num;}; int a::_num = 0;//initialization succeeds class B:p ublic a{public:void fun () const{_num++;//correct, const function can change static member variable}private:int num;};
This article is from the "Pawnsir It Road" blog, so be sure to keep this source http://10743407.blog.51cto.com/10733407/1748567
Summary of features of C + + static member variables and test cases