Sometimes some data in the program needs to be permanently saved or called globally for other reasons, but the global data is dangerous for development. Static is introduced here, which is very useful.
I understand static as follows:
When an object is generated by a common member in a class, each member is associated with an object. Therefore, an object can call its own members, so this pointer makes sense. For static declared members, this pointer is only associated with the class. this member is not instantiated when an object is generated, therefore, the object cannot be called for this member, and the this pointer is meaningless.
In addition, static is advantageous, can replace some global functions, and has encapsulation attributes. The Code is as follows:
Test. h
# Ifndef TEST_H
# Define TEST_H
# Include <iostream>
Using namespace std;
Class Test
{
Public:
Test ();
Void set ();
Void print ();
Virtual ~ Test ();
Protected:
Private:
Static int num; // Private static member with Encapsulation
// Static int num = 0; // cannot be defined during declaration. But const static int num = 0; can be defined,.
};
# Endif // TEST_H
# Include "../include/Test. h"
Int Test: num = 0; // static member Initialization
Test: Test ()
{
// Ctor
// This-> num = 0; // The static member can be defined only once and cannot be defined in class initialization.
}
Void Test: set ()
{
Num ++;
}
Void Test: print ()
{
Cout <num <endl;
}
Test ::~ Test ()
{
// Dtor
}
# Include <iostream>
# Include "./include/Test. h"
Using namespace std;
Int main ()
{
Test t;
// T. num = 9; // Private Members cannot use
T. set ();
T. print ();
Return 0;
}
Hope the majority of users will give guidance...
From the column Leeboy_Wang