Go to the Static keyword in C + +

Source: Internet
Author: User

Static in C + + has two uses for the use of static for C + +: Static in process-oriented programming and in object-oriented programming. The former applies to ordinary variables and functions, and does not involve classes; the latter mainly describes the role of static in classes. First, the STATIC1 in the process design, static global variables before the global variable, plus the keyword static, the variable is defined as a static global variable. Let's first give an example of a static global variable, as follows:
1#include <iostream>2 using namespacestd; 3   4 Static intN//defining static global variables5   6 voidfn ()7 {  8n++; 9cout<<n<<Endl; Ten }   One    A intMainvoid)   - {   -n = -;  thecout<<n<<Endl;  - fn ();  -     return 0;  -}


    • Static global variables have the following characteristics:
    • The variable allocates memory in the global data area;
    • Uninitialized static global variables are automatically initialized by the program to 0 (the value of the automatic variable is random unless it is explicitly initialized);
    • A static global variable is visible in the entire file that declares it, and is invisible outside of the file;
Static variables allocate memory in the global data area, including the static local variables that will be mentioned later. For a complete program, the distribution in memory is as follows:
Code Area
Global Data area
Heap Area
Stack area
The dynamic data generated by new in the general program is stored in the heap area, and the automatic variables inside the function are stored in the stack area. Automatic variables generally free up space as the function exits, and static data (even static local variables inside the function) is stored in the global data area. The data in the global data area does not free up space because of the function's exit. Careful readers may find that the code in Example 1 will [CPP] static int n; Define static global variable to [CPP] int n; Defining a global Variables program works as expected. It is true that defining global variables allows for the sharing of variables in a file, but there are also the benefits of defining static global variables: Static global variables cannot be used by other files, variables with the same name can be defined in other files, and no conflicts occur; You can change the sample code above to read as follows: [CPP] File1
    • using namespace Std;
    • VOID Fn ();
    • staticint//Defining a statically global variable
    • intvoid{
    • cout<<n<<endl;
    • return 0;
    • #include <iostream>
    • Usingnamespace
    • externint
    • void{
    • cout<<n<<endl;
    • Compile and run the program, and you will see that the code above can be compiled separately, but there is an error at run time. Try to
[CPP] static int n; Define static global variable to [CPP] int n; Define global variables compile and run the program again, carefully understand the difference between global variables and static global variables. 2, static local variable before the local variable, plus the keyword static, the variable is defined as a static local variable. Let's first give an example of a static local variable, as follows: [CPP] #include <iostream>
    • Usingnamespace
    • void
    • intvoid{
    • FN ();
    • return 0;
    • void{
    • staticint cout<<n<<endl;
    • }
Typically, a variable is defined in the body of the function that allocates stack memory to the local variable whenever the program runs to the statement.  However, as the program exits the function body, the system will retract the stack memory, and the local variables are invalidated accordingly. But sometimes we need to save the values of the variables between the two calls. The usual idea is to define a global variable to implement.  In this way, the variables are no longer part of the function itself, and are no longer only controlled by the functions, which inconvenience the maintenance of the program. Static local variables can solve this problem. Static local variables are saved in the global data area, not in the stack, and each time the value is persisted to the next call until the next time the new value is assigned. Static local variables have the following characteristics: (1) The variable allocates memory in the global data area, and (2) the static local variable is first initialized when the program executes to the declaration of the object, that is, the subsequent function call is no longer initialized, and (3) the static local variable is usually initialized at the declaration, if not explicitly initialized, the program automatically Initialized to 0; (4) It always resides in the global data area until the program finishes running. But its scope is a local scope, when the function or block of statements defining it ends, its scope ends; 3. Static functions are defined as static functions by adding the static keyword before the return type of the function. A static function differs from a normal function in that it can only be seen in the file that declares it and cannot be used by other files. Examples of static functions: [CPP] #include <iostream>
    • Usingnamespace
    • staticvoid//Declaration of statically function
    • intvoid{
    • return 0;
    • void//define static function {
    • int cout<<n<<endl;
    • Benefits of defining static functions:
Static functions cannot be used by other files, functions with the same name can be defined in other files, no conflicts occur, second, object-oriented static keywords (static keywords in class) 1, static data members are prefixed with the keyword static before the declaration of the data member within the class. The data member is a static data member within the class. Give an example of a static data member first. [CPP] #include <iostream>
  • Usingnamespace
  • Class{
  • Private int A, b, C;
  • staticint//declares the data member public at rest :
  • intintint void getsum ();
  • int//define and initialize static data members
  • int int int{
  • This this->b = b;
  • This sum + = A+b+c;
  • void Myclass::getsum ()
  • cout<< "sum=" <<sum<<endl;
  • intvoid{
  • M.getsum ();
  • N.getsum ();
  • return 0;
  • As you can see, static data members have the following characteristics:
    • 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. Therefore, the value of the static data member is the same for each object, and its value can be updated;
    • Static data members are stored in the global data area. Static data members are defined when they are allocated space, so they cannot be defined in a class declaration. In Example 5, the statement int myclass::sum=0 is defined as a static data member;
    • Static data members comply with PUBLIC,PROTECTED,PRIVATE access rules like normal data members;
    • Because static data members allocate memory in the global data area, all object shares of this class are shared, so it does not belong to a particular class object, its scope is visible when no class object is produced, that is, we can manipulate it without producing an instance of the class;
    • Static data member initialization differs from general data member initialization. The static data member is initialized in the following format:
Data type >< class name >::< static data member name >=< value
    • The static data members of a class are accessed in two ways:
Class object name >.< static data member name or class type name >::< static data member name > If the access permission of the static data member (that is, the member of public), the static data member can be referenced in the program according to the above format;
    • 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;
    • There are two advantages to using static data members compared to global variables:
    1. 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;
    2. Information hiding can be implemented. A static data member can be a private member, while a global variable cannot;
2. Static member functions like static data members, we can also create a static member function that serves the entire service of a class rather than a specific object of a class. Static member functions, like static data members, are internal implementations of the class and are part of the class definition. Ordinary member functions generally imply a this pointer, which points to the object of the class itself, 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-&GT;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 non-static data members that belong to a class object, nor can it access a non-static member function, which only calls the rest of the static member functions. Here is an example of a static member function. [CPP] #include <iostream>
  • Usingnamespace
  • Class{
  • Private int A, b, C;
  • staticint//declares the data member public at rest :
  • intintint static void Getsum (); Declaring a static member function
  • int//define and initialize static data members
  • int int int{
  • This this->b = b;
  • This sum + = A+b+c; Non-static member functions can access static data members
  • void Myclass::getsum ()//static member function implementation
  • cout<<a<<endl; Error code, a non-static data member
  • "Sum="}
  • int main (void)
  • Myclass M (1, 2, 3);
  • Myclass N (4, 5, 6);
  • Myclass::getsum ();
  • Return}
For static member functions, you can summarize the following points:
    • A function definition that appears outside the class body cannot specify a keyword static;
    • Static members can be accessed from one another, including static member functions that access static data members and access static member functions;
    • Static member functions and static data members can be accessed arbitrarily by non-static member functions;
    • Static member functions cannot access non-static member functions and non-static data members;
    • 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;
    • Call a 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:
The class name >::< static member function name, or parameter table, to invoke the static member function of the class.

Go to the Static keyword in C + +

Related Article

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.