A data member that is preceded by a static decoration on a type, is subordinate to the class, becomes a static data member of the class, also known as a "class variable"
A static data member is shared by all objects of that class (that is, the data field in all objects is actually in the same memory location)
Static data is assigned an initial value in the implementation file in the following format:
Type Classname::static_var = Value;
The return value type is preceded by the static modifier's member function, which is called a statics member function, and they cannot invoke a non-static member function;
A static member (data, function) of a class can be accessed either through an object or through a class name class;
#include <iostream>using namespacestd;classtest{Static intcount; Public: Test () {count++; } ~test () {count--; } Static intHow_many () {returncount;}};intTest::count =0;voidprint (Test t) {cout<<"Tests:"<< T.how_many () <<Endl;}intMain () {Test T1; cout<<"test#"<< Test::how_many () <<Endl; Test T2=T1; cout<<"test#"<< Test::how_many () <<Endl; Print (T2); cout<<"test#"<< T1.how_many () <<","<< T2.how_many () <<Endl;
return 0;}
Constant members in a class
Data members that use const adornments, called constant data members of a class, cannot be changed throughout the life of the object;
A const data member can only be set in the initialization list of a constructor, and is not allowed to be set by assignment in the function;
If the member function is modified with const, the member function cannot modify the data member of the class when it is implemented, that is, the statement of the object state cannot be changed in the function body;
If the object is defined as a constant, it can only call a const-decorated member function, and the other member function does not allow invocation;
C + + Programming Method 3: Static members in a class