Static member: the member that added the static keyword before the description. in C + +, a static member is an entire class rather than an object, and a static member variable stores only one copy for all objects to be shared. So it can be shared across all objects.
why: Using static member variables to implement data sharing between multiple objects does not break the hidden principle, guaranteeing security and saving memory.
Program Examples:
Class Crectangle{private:int W, h;static int ntotalarea;//static member variable static int ntotalnumber;public:crectangle (int w_,int H_ ); ~crectangle (); static void Printtotal (); static member function};
To access a static member:
1) class Name:: member name
crectangle::P rinttotal ();
2) object name. Member Name
Crectangle R; r.printtotal ();
3) member name with Pointer
Crectangle * p = &r; p->printtotal ();
4) Reference. Member name
Crectangle & ref = r; int n = ref.ntotalnumber;
Note tips:
in a static member function, Non-static member variables cannot be accessed, and non-static member functions cannot be called.
For example:
void Crectangle::P rinttotal () {cout << w << "," << ntotalnumber << "," << Ntotalarea << Endl Wrong}cretangle::P rinttotal (); It doesn't explain, W exactly belongs to that object? Crectangle::crectangle (int w_,int h_) {w = W_;h = H_;ntotalnumber ++;ntotalarea + = w * H;} Crectangle::~crectangle () {ntotalnumber--;ntotalarea-= w * h;} void Crectangle::P rinttotal () {cout << ntotalnumber << "," << Ntotalarea << Endl;}
cause of error:
When using the Crectangle class, the copy constructor is sometimes called to generate a temporary hidden Crectangle object, when a function that invokes a Crectangle class object as a parameter is called, and a function that invokes a Crectangle class object as the return value is called. Temporary objects call Destructors when they die, reducing the values of ntotalnumber and Ntotalarea, but these temporary objects do not increase the values of ntotalnumber and Ntotalarea when they are generated.
Talk about C + + Session 3: Static members (variables, functions)