C + + Intermediate Statickeyword

Source: Internet
Author: User

Static as the name implies is a quiescent meaning. Here I would like to talk about the relevant system Statickeyword role, of course, this is mainly for the development of language C and C + + roles, in the role of information, etc., please find another. In the comments must be inappropriate, please bold to throw bricks. Soft, the content of the text quoted a lot of information on the Internet.

Static from the macroscopic, there are two main methods of use, one is process-oriented design, and the other is object-oriented design. The former mainly involves the use of variables and functions. The latter includes the same time as the former method of use. There are also methods to use in the class.

static (C language) for process design

When it comes to static usage in process design, let's start with a bit of an episode, historically speaking. The C program has been composed of the following parts:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvd2vucmvuahvhmdg=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast ">

Body Segment

The part of the machine instruction that the CPU is running. Normally, the body segment is shareable. So even if the Environment Pointer Environment table environment string Run program (such as text editing programs, C compiler, S H e l L, etc.) in memory also only need a copy, in addition, the body is often read-only, to prevent the program because of an accident and change its own instructions.

Initializing data Segments

This segment is often referred to as a data segment, which includes variables that need to be assigned an initial value in the program. The initialized global variables and static variables are stored here.

Like what. Description of the C program, regardless of function: 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 a symbol)", where uninitialized global variables and static variables are stored. Before the program starts running. The kernel initializes this segment to 0. 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

Need to be allocated by the program ape Release Management , if the program ape does not release, the program ends may be recycled by the OS.

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 compiler voluntarily assigns the release management itself .

Local variables and the return address of each function call, and the caller's environment information (such as some machine registers) are stored in the stack. The newly called function allocates storage space for its own active and transient 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. Therefore, a variable in an instance of a function call never affects a variable in an instance of a function call.

A. Local variables

B. Returning an address when a function is called

C. Caller's environment information (e.g. some machine registers)

In this I first put the static internal mechanism and 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 when the program starts executing.

Because functions are called in program execution, static data members 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 a class declaration, and the second is the internal implementation of the class definition. There is a member function definition for the class, and the third is the global data declaration and definition before 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 simply declares the "size and specification" 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 class declarations, because that can result in multiple source files that use the class. Define it repeatedly.

Static is introduced to inform the compiler. Store variables in the program's static store instead of on-stack space. Static data members are initialized sequentially in the order in which they are defined, and note 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 owned by all objects. Therefore, for multiple objects. Static data members are stored in 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 is capable of being updated.

Simply update the value of the static data member once, ensuring that all objects access the same value after the update. This can improve time efficiency.

static local variable

Static local variables belong to static storage mode. It has the following characteristics:

(1) A static local variable defines its lifetime as the entire program life cycle within a function, but its scope is still the same as its own active variable , which can only be used within the function that defines the variable.

After exiting the function, the variable continues to exist. But you can't use it.

(2) If the static local variables of the basic type are not assigned the initial value at the time of declaration , then the system will voluntarily give 0 values.

The value of the self-active variable is indefinite 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 whole program life cycle. Although it cannot be used after a function that defines it, it can continue to be used if the function that defines it is called again. and saves the value left after the previous call. Therefore, you can consider using static local variables when you call a function multiple times and require the values of certain variables to be preserved between calls . Although global variables are used to achieve this. However, global variables can sometimes cause unexpected side effects. Therefore, 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 , 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 only valid within the source file that defines the variable. It cannot be used in other source files of the same source program.

Because the scope of a static global variable is limited to a single source file , it can only be common for functions within that source file, so it avoids causing errors in other source files.

It can be seen from the above analysis that changing the global variable to a static variable changes its scope. Limits its scope of use .

static function

Suppose that a function defined in a source file can only be called by a function in this file. Instead of being called by functions in other files in the same program, this function is called a static function.


Defines a static function. Just add a "static" keyword to the function type before you can. For example, see the following:

static function type function name (function Reference) {...}

Keyword "static". The translation into Chinese is "static", 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 different people write different functions. Don't worry about custom functions. Whether it will have the same name as the function in other files, because it has no relation .

ii. static in object-oriented design (c + + language) static data member

Precede the declaration of a data member within a class with keywordstatic, which is the static data member within the class.

Give a sample 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 of the program and are shared by all objects of that type. Other words. A static data member is owned by all objects of the class.

For multiple objects of this class, a static data member allocates only one memory for common use by all objects.

(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. statement int test::m_nstest1= 10; is a static data member that is defined.

(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 belonging to this class are shared, so it is not part of a particular class object, and its scope is visible when no class object is produced, that is, when an instance of the class is not produced. We are able to 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, interest is the same for each instance. Therefore, interest should be set as a static data member of the deposit class. This has two advantages, the first one. Regardless of how many deposit class objects are defined. Interest data members share the memory assigned to the global data area. So storage space is saved. Secondly, once the interest needs to be changed, the interest of all deposit-taking objects will change only once;

(8). Compared with global variables. There are two advantages to using static data members:

A. Static data members do not enter the program's global namespace. Therefore, there is no possibility of conflict with other global names in the program;

B. Ability to implement information hiding. 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 all services of a class instead of a detailed object for a class. Ordinary member functions generally imply a this pointer, since ordinary member functions are always detailed to the detailed object of a class.

Typically, this is the default.

such as the function fn () is actually THIS->FN (). However, compared to normal functions, static member functions are not associated with objects of whatever. Therefore, it does not have this pointer. In that sense. It cannot access no-static data members that belong to class objects . You also cannot access the No-static member function. It can only invoke the rest of the static member functions.

About static member functions can be summed up in the following points:

(1). The function definition outside the class body cannot specify keywordstatic ;

(2). Static members can access each other , including static member functions visiting static data members and visiting static member functions;

(3). Non-static member functions are free to access static member functions and static data members;

(4). Static member functions can not access non-static member functions and non-static data members, only access to static ;

(5). Because there is no additional overhead for this pointer. Therefore, the static member function will have a little increase in speed compared with the global function of the class;

(6). Call the static member function. Ability to use member access operators (.) and (a) call a static member function for an object of a class or pointer to a class object, or you can use the following format, for example:

Class name >::< static member function name > ("Tables")

such as: Test::P rintstatic (), call the static member function of the class.

However, follow the public,protected,private access rules as well.


Reportpublic,protected,privateAccess rules

First: Private, public, protected access to the scope of the number of visitors.

Private : Can only be made by 1. The function in this class, 2. Access to its friend function.

Cannot be interviewed by any other. Objects of this class cannot be interviewed.

protected : able to be 1. Functions in this class, 2. Functions of subclasses, and 3. Their friend functions are interviewed.

But cannot be interviewed by the object of the class.

Public : able to be 1. Functions in this class, 2. The function of the subclass, 3. Its friend function can also be visited by 4. The object of the class.

Note: The Friend function contains 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 properties 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;

For example, see the following:

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 are 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. Other members are not visible.


So, when the public continues. Objects of a derived class can access public members in the base class. member functions of derived classes can access public and protected members in the base class. Here, it is important to distinguish between the objects of the derived class and the member functions in the derived class 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 interviewed by directly derived classes. And can no longer go down.
For protection continue mode:
The continuation of this way is the same as in the case of private continuation. The difference between the two is that the members of the derived class have different visibility to the base class members.
The above-mentioned visibility is also accessibility. There is another way of saying about accessibility.

In such a rule, an object that is called a derived class visits the base class as a level interview. A derived class that is called a derived class is asked for access to the base class as a vertical interview.
General rules such as the following:
When the public continues, the level of access and vertical visits are not restricted to the public members of the base class;
When private continues, the level of access and vertical visits to the public members of the base class are also not accessible;
When protection continues. For vertical access the same as public continuation, for horizontal access is the same as private continuation.


For private members in the base class. Can only be asked by member functions and friend functions in the base class. Cannot be interviewed by other functions.
The relationship between a base class and a derived class
No matter what a class can derive from a new class, a derived class can also derive a new class. So. The base class and derived class are relative.
The relationship between a base class and a derived class can have several descriptive narratives, such as the following:
1. Derived classes are the basis of the details of the class
The hierarchy of classes usually reflects some kind of real model in the objective world. In such a case. It is not difficult to see that a base class is an abstraction of several derived classes, whereas derived classes are the details of a base class. The base class extracts the public characteristics of its derived class, and the derived class changes the abstract class to a practical type by adding 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 such a situation. Then. Derived classes are an implementation of the abstract base class. Can be seen as a continuation of a base class definition.

This is also a common use of derived classes.
3. Derived classes are a combination of base classes
As you go on more. There is more than one base class for a derived class. The derived class will then be a combination of all the base class behavior.


The method by which a derived class distinguishes itself from a base class is by adding data members and member functions. Therefore, the continuation mechanism will make it possible to create a new class simply by stating the difference between the new class and the existing class. So a lot of the original program code can be reused, so some people call the class is "reusable software components."


Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.

C + + Intermediate Statickeyword

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.