Use of a static (scope and storage mode)
1. Scope----------> Hide
Static functions are similar to static global variables (static functions cannot be used by other files; functions with the same name can be defined in other files, and no conflicts will occur)
int a = 10;
void Add ()
{
static int a=0; The function is hidden and only works within the function
printf ("A =%d", a);
}
int main ()
{
' a++;
Add ();
printf ("A =%d", a);
}
Results: A=0 a=10;
function (static does not contain this pointer)
A. Static functions can only access static member variables (this pointer is not required)
B. Static functions cannot access ordinary member functions, but vice versa (static member functions do not have this pointer)
2. Storage mode--------------> Shared (its value will be saved, the next call will remain the last value)
A. Local variable: After the function executes the variable, the variable will not be released and continue saving
B. Global variable: Indicates that a variable can be accessed globally
C. class member variable: Indicates that the variable is of the whole class (all objects are common to this variable, it is not a private of an object)
Use of two const (only readable work energy)
- CONST constant: Initialized when defined and cannot be changed later.
- Const parameter: func (const int a) {}; The parameter cannot be changed in a function
- Const modifier CLASS member function: This function can only read-only for member variables
- Can be used as an overloaded function void func (Test * const this (default)) const---------=>void func (const Test * const This): The function only has read Yes, cannot modify its variables
Because the this pointer is a constant and cannot be changed, it is similar to the static member function, where ordinary functions can access the constant member function and vice versa. Constant member functions can only access constant member variables
Three different points
Static: Statically variable, only related to the class, and object-independent, even if no object can call static functions and variables.
Data type class Name:: static data member name = value int test::a = 10;
Const: Initialization must have constructor initialization and different object const values are not the same.
Summary and use of C + + const and static