Static as the name implies. In this I would like to systematically tell about the role of the static keyword, of course, mainly to tell it in the development of language C and C + + role, in other aspects of the role please find additional information. In the explanation certainly has the inappropriate place, please everybody boldly throws the brick, does not relent, the text content quoted many online information.
Static from the macroscopic, there are two main usages, one is the process-oriented design, the other is object-oriented design. The former mainly involves the use of variables and functions, while the latter includes the use of the former, as well as the usage in the class.
static (C language) for process design
When talking about static usage in process design, let's start with an episode, historically, the C program has been composed of the following parts:
Body Segment
The part of the machine instruction that the CPU executes. Normally, the body segment is shareable, so even a program that is executed by a regular environment pointer environment string (such as a text editor, C compiler, S H e L, etc.) can only have one copy in memory, and the body segment is often read-only to prevent the program from modifying its own instructions due to an accident.
Initializing data Segments
This segment is often referred to as a data segment, which contains variables that need to be assigned an initial value in the program. The initialized global variables and static variables are stored here. For example, a description outside any function in the C program: int maxcount = 99; Causes this variable to be stored in the initialization data segment with an initial value.
A. Initialized global variables
B. Initializing a static variable
non-initialized data segment
This segment is often referred to as the BSS segment, which is derived from an operator of the early assembler, meaning "block started by symbol (blocks starting with symbols)", where uninitialized global variables and static variables are stored. The kernel initializes this segment to 0 before the program begins execution. Description outside the function: Long sum[1000]; Causes this variable to be stored in a non-initialized data segment.
A. Uninitialized global variables
B. Uninitialized static variables
Heap
Release management needs to be assigned by the programmer , and if the programmer does not release it, it may be recycled by the OS at the end. Dynamic storage allocations are typically performed in the heap. Such functions as malloc in the program, Calloc,realloc, and so on are assigned from this side. The heap is assigned from the bottom up.
Stack
The release tube is automatically assigned by the compiler. Local variables and the return address of each function call, and the caller's environment information (for example, some machine registers) are stored in the stack. The newly called function allocates storage space for its automatic and temporary variables on the stack. By using the stack in this way, the C function can be called recursively. The recursive function uses a new stack frame each time it calls itself, so a variable in one function call instance never affects a variable in another function call instance.
A. Local variables
B. Returning an address when a function is called
C. Caller's environment information (for example, some machine registers)
In this I first put the internal mechanism of static and the advantages mentioned before, originally wanted to put in object-oriented design, but its importance changed the original intention:
The internal mechanism of static:
A static data member must exist at the beginning of a program run. Because a function is called in a program run, a static data member cannot allocate space and initialization within any function.
In this way, its spatial allocation has three possible places, one is the header file as the outer interface of the class, there is the class declaration, and the second is the inner implementation of the class definition, there is the member function definition of the class, and the third is the global data declaration and definition in front of the main () function of the application.
Static data members are actually allocated space, so they cannot be defined in the declaration of a class (only data members can be declared). A class declaration declares only "dimensions and specifications" of a class and does not actually allocate memory, so it is wrong to write a definition in a class declaration. It also cannot be defined externally in the header file for the class declaration, because that would cause duplicate definitions in multiple source files that use the class.
Static is introduced to tell the compiler that the variables are stored in the program's static store rather than on the stack, and that static data members are initialized sequentially in the order in which they are defined, noting that when static members are nested, the nested members are guaranteed to be initialized. The order of elimination is the inverse order of the initialization.
The advantages of static:
Can save memory because it is public to all objects, so for multiple objects, static data members are stored only one place for all objects to be shared. The value of a static data member is the same for each object, but its value can be updated. As long as the value of the static data member is updated once, it is guaranteed that all objects access the same value after the update, which can improve time efficiency.
static local variable
Static local variables belong to static storage, which has the following characteristics:
(1) A static local variable defines its lifetime within a function as the entire program life cycle, but its scope is still the same as an automatic variable , which can only be used within the function that defines the variable. After exiting the function, it cannot be used even though the variable continues to exist.
(2) If a static local variable of the basic type is not assigned an initial value at the time of declaration , the system automatically assigns 0 values. The value of the automatic variable is indeterminate if it is not assigned the initial values.
According to the characteristics of static local variables, it can be seen that it is a lifetime of the entire program life cycle. Although it cannot be used after the function that defines it, it can continue to be used if the function that defines it is called again, and the value left after the previous call is saved. Therefore, you can consider static local variables when you call a function multiple times and require the values of certain variables to be preserved between calls . Although this can be achieved with global variables, global variables sometimes cause unintended side effects, so it is advisable to use local static variables.
#include <stdio.h> #include <stdlib.h> void Test () { static int tmpvalue = 0; printf ("value =%d\n", ++tmpvalue);} int main () {for (int index = 0; index <; ++index) { Test () } GetChar (); return 0;}
Global Variables
A static global variable is formed by the description of the global variable (external variable), preceded by static. Global variables themselves are static storage, and static global variables are, of course, static storage methods. The two are not different in how they are stored.
The difference between the two is:
(1). The scope of a non-static global variable is the entire source program , and when a source program consists of multiple source files , non-static global variables are valid in each source file.
(2). while a static global variable restricts its scope, it is valid only within the source file that defines the variable and cannot be used in other source files of the same source program. Because the scope of a static global variable is limited to one source file , it can be common only for functions within that source file, so you avoid causing errors in other source files.
From the above analysis, it can be seen that changing the global variable to a static variable changes its scope and limits its scope of use .
static function
If a function defined in a source file can only be called by a function in this file, but not by a function in the other file of the same program, this function is called the static function.
To define a static function, simply add a "static" keyword before the function type, as follows:
static function type function name (function parameter table) {...}
The keyword "static", translated into Chinese, is "still", so the internal function is also called the static function. But the meaning of "static" here does not mean storage, but the scope of the function is limited to this file .
The advantage of using intrinsic functions is that when different people write different functions, they don't have to worry about the functions they define, or whether they have the same name as the functions in other files, because the same name doesn't matter .
ii. static in object-oriented design (c + + language)
static data member
Precede the declaration of a data member within a class with the keyword static, which is a static data member within the class. Give an example of a static data member first.
#include <stdio.h> #include <stdlib.h> class Test{public:test () {} ~test () {} Test (const test& T) {if (*this! = t) {this->m_ntest1 = T.m_ntest1; This->m_ntest2 = T.m_ntest2; This->m_ntest3 = T.m_ntest3; }} test& operator= (const test& t) {if (*this! = t) {this->m_ntest1 = T.M _ntest1; This->m_ntest2 = T.m_ntest2; This->m_ntest3 = T.m_ntest3; } return *this; } void PrintOut () {//printf ("test_1 =%d Test_2 =%d Test_3 =%d\n", M_nstest1, M_nstest2, M_NSTEST3);//Error printf ("test_1 =%d Test_2 =%d Test_3 =%d\n", M_ntest1, M_ntest2, M_NTEST3); } static void Printstatic () {printf ("test_1 =%d Test_2 =%d Test_3 =%d\n", M_nstest1, M_nstest2, m_nstes T3); printf ("test_1 =%d Test_2 =%d Test_3 =%d\n", M_ntest1, M_ntest2, M_NTEST3);//error} Public:int m_nTest1; static int m_nstest1; Protect:int M_ntest2; static int m_nstest2; Private:int M_ntest3; static int m_nstest3;}; int test::m_nstest1 = 10;int Test::m_nstest2 = 20;int Test::m_nstest3 = 30; int test::m_nstest1 = 10;int Main () {Test T; T.printout (); T.printstatic ();//Error Test::P rintstatic (); GetChar (); return 0;}
Static data members have the following characteristics:
(1). For non-static data members, each class object has its own copy. Static data members are treated as members of the class. Regardless of how many objects of this class are defined, static data members have only one copy in the program and are shared by all objects of that type. In other words, a static data member is common to all objects of that class. For multiple objects of this class, static data members are allocated only once for all objects to be shared.
(2). Static data members are stored in the global data area. A static data member is defined only when space is allocated, so it cannot be defined in a class declaration . In the example above, the statement int test::m_nstest1= 10; is a static data member;
(3). Static data members and ordinary data members comply with public,protected,private access rules;
(4). Because static data members allocate memory in the global data area, all objects of this class are shared, so it does not belong to a particular class object, and its scope is visible when no class object is produced, that is, when there is no instance of the class, we can manipulate it;
(5). Static data member initialization differs from general data member initialization. The static data member is initialized in the form of the data type >< class name >::< static data member name >=< value, such as: int test::m_nstest1 = 10;
(6). Static data members of a class have two types of Access: Class object name >.< static data member name, or class type name >::< static data member name.
(7). Static data members are used primarily when each object has the same property. For example, for a deposit class, the interest is the same for each instance. Therefore, interest should be set as a static data member of the deposit class. There are two benefits, first, regardless of how many deposit class objects are defined, the interest data members share the memory allocated in the global data area, thus saving storage space. Second, once the interest needs to be changed, the interest of all the deposit classes will change as soon as it is changed;
(8). Using static data members has two advantages over global variables:
A. Static data members do not enter the program's global namespace, so there is no possibility of conflicts with other global names in the program;
B. Information hiding can be implemented. A static data member can be a private member, while a global variable cannot;
Static member function
#include <stdio.h> #include <stdlib.h> class Test{public:test () {} ~test () {} Test (const test& T) {if (*this! = t) {this->m_ntest1 = T.m_ntest1; This->m_ntest2 = T.m_ntest2; This->m_ntest3 = T.m_ntest3; }} test& operator= (const test& t) {if (*this! = t) {this->m_ntest1 = T.M _ntest1; This->m_ntest2 = T.m_ntest2; This->m_ntest3 = T.m_ntest3; } return *this; } void PrintOut () {//printf ("test_1 =%d Test_2 =%d Test_3 =%d\n", M_nstest1, M_nstest2, M_NSTEST3);//Error printf ("test_1 =%d Test_2 =%d Test_3 =%d\n", M_ntest1, M_ntest2, M_NTEST3); } static void Printstatic () {printf ("test_1 =%d Test_2 =%d Test_3 =%d\n", M_nstest1, M_nstest2, m_nstes T3); printf ("test_1 =%d Test_2 =%d Test_3 =%d\n", M_ntest1, M_ntest2, M_NTEST3);//error} Public:int m_nTest1; static int m_nstest1; Protect:int M_ntest2; static int m_nstest2; Private:int M_ntest3; static int m_nstest3;}; int test::m_nstest1 = 10;int Test::m_nstest2 = 20;int Test::m_nstest3 = 30; int test::m_nstest1 = 10;int Main () {Test T; T.printout (); T.printstatic ();//Error Test::P rintstatic (); GetChar (); return 0;}
The static member function, which serves the entire service of a class instead of a specific object for a class. Ordinary member functions generally imply a this pointer, because ordinary member functions are always specific to the specific object of a class. Typically, this is the default. such as the function fn () is actually THIS->FN (). However, compared to a normal function, a static member function does not have the this pointer because it is not associated with any object. In this sense, it cannot access the No-static data member that belongs to the class object , nor can it access the No-static member function, which can only invoke the rest of the static member functions.
For static member functions, you can summarize the following points:
(1). A function definition that appears outside the class body cannot specify a keyword static ;
(2). static members can be accessed from each other , including static member functions accessing static data members and accessing static member functions;
(3). Static member functions and static data members can be accessed arbitrarily by non-static member functions;
(4). Static member functions cannot access non-static member functions and non-static data members, and can only access static ;
(5). Because there is no additional overhead for this pointer, the static member function has a slight increase in speed compared to the global function of the class;
(6). Call the static member function, which can be accessed with the member access operator (.) and (-) call a static member function for an object of a class or pointer to a class object, or you can use the following format directly:
Class name >::< static member function name > (parameter table)
such as: Test::P rintstatic (), call the static member function of the class.
However, you should follow the Public,protected,private access rules as well.
Reportpublic,protected,privateAccess rules
First: Private, public, access to the Protected Access label.
Private : Only by 1. Functions in this class, 2. Access to its friend function.
The object of the class cannot be accessed by any other access.
protected : Can be 1. Functions in this class, 2. Functions of subclasses, and 3. Its friend function is accessed.
But cannot be accessed by objects of that class.
Public : Can be 1. Functions in this class, 2. A function of a subclass, 3. Its friend function is accessed by 4. The object of the class.
Note: The friend function consists of 3 types: Ordinary non-member functions set as friends, member functions of other classes set as friends, and all member functions in the friend class.
Second: The class inherits the method property changes.
Private property cannot be inherited.
with private inheritance, the protected and public properties of the parent class become private in subclasses;
With protected inheritance, the protected and public properties of the parent class become protected in the subclass;
With public inheritance, the protected and public properties in the parent class do not change;
As shown below:
Public:protected:private:
Public inherited public protected not available
protected inherited protected protected not available
Private Inherit private private is not available
protected inheritance and private inheritance can reduce access rights.
to further understand the differences in the visibility of the three different continuation modes in their members, the following is discussed from three different perspectives.
For public continuation mode:
(1) The visibility of the base class members to their objects:
Public members are visible, others are not visible. Here the protection members are identical to the private members.
(2) The visibility of a base class member on a derived class:
Public and protected members are visible, and private members are not visible. The protection of Members here is the same as public members.
(3) The visibility of a base class member on a derived class object:
Public members are visible and other members are not visible.
Therefore, when the public continues, the objects of the derived class can access the public members in the base class, and the member functions of the derived class can access the public and protected members in the base class. Here, it is important to distinguish between objects of derived classes and member functions in derived classes that have different access to the base class.
For private continuation methods:
(1) The visibility of the base class members to their objects:
Public members are visible and other members are not visible.
(2) The visibility of a base class member on a derived class:
Public and protected members are visible, and private members are invisible.
(3) The visibility of a base class member on a derived class object:
All the members are invisible.
Therefore, when private continues, the members of the base class can only be accessed by directly derived classes, and cannot proceed further down.
For protection continue mode:
This continuation is the same as in the case of a private continuation mode. The difference between the two is that the members of the derived class have different visibility to the base class members.
The visibility referred to above is also accessibility. There is another way of saying about accessibility. In this rule, objects that are called derived classes are accessed horizontally for the base class, which is called a derived class's access to the base class as a vertical access.
The general rules are as follows:
When the public continues, horizontal access and vertical access are not restricted to the public members in the base class;
When private continues, horizontal access and vertical access are not accessible to public members in the base class;
When protection continues, for vertical access same as public continues, for horizontal access is the same as private continuation.
Private members in a base class can only be accessed by member functions and friend functions in the base class, not by other functions.
The relationship between a base class and a derived class
Any class can derive a new class, and derived classes can also derive new classes, so the base and derived classes are relative.
The relationship between a base class and a derived class can be described in the following ways:
1. Derived classes are materialization of base classes
The hierarchy of classes usually reflects some kind of real model in the objective world. In this case, it is not difficult to see that the base class is an abstraction of several derived classes, whereas derived classes are materialized by the base class. The base class extracts the public characteristics of its derived class, and the derived class changes the abstract class to some useful type by increasing the behavior.
2. A derived class is a continuation of a base class definition
An abstract base class is defined first, and some operations in that base class are not implemented. Then define non-abstract derived classes to implement the operations defined in the abstract base class. For example, a virtual function is a condition of this kind. At this point, the derived class is the implementation of the abstract base class and can be seen as a continuation of the base class definition. This is also a common method for derived classes.
3. Derived classes are a combination of base classes
When multiple continuation, a derived class has more than one base class, at which point the derived class will be a combination of all base class behavior.
The method by which a derived class distinguishes itself from a base class is to add data members and member functions. Therefore, the continuation mechanism will make it possible to create a new class by simply stating the difference between the new class and the existing class, so that a large number of the original program code can be reused, so some people call the class "reusable software artifacts."
The static keyword in C + +