Summary of the static keyword in C + + (reproduced)

Source: Internet
Author: User

The static of C + + has two usages: static in process-oriented programming and static 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.

1. Static for process design
1.1 Static global variables
Before the global variable, the variable is defined as a static global variable, plus the keyword static. Let's first give an example of a static global variable, as follows:
Example 1
#include <iostream.h>
VOID Fn ();
static int n; Defining static global Variables
void Main ()
{
n=20;
cout<<n<<endl;
FN ();
}

VOID Fn ()
{
n++;
cout<<n<<endl;
}
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. The attentive reader may find that the code in Example 1 will "static int n; Define static global variable "to " int n; Define the global variables. The program is still functioning normally. It is true that defining global variables allows for the sharing of variables in files, but there are also the following benefits of defining static global variables:
• Static global variables cannot be used by other files;
• Variables of the same name can be defined in other files and no conflicts will occur;

You can change the example code above to read as follows:
Example 2
File1
#include <iostream.h>
VOID Fn ();
static int n; Defining static global Variables
void Main ()
{
n=20;
cout<<n<<endl;
FN ();
}

//file2
#include <iostream.h>
extern int n;
VOID fn ()
{
 n++;
  cout<<n<<endl;
}
Compile and run Example 2, you will find that the above code can be compiled separately, but there is an error at run time. Try to   "static int n; Define static global variable " to   " int n; Define global variables '
Run the program again, and carefully understand the difference between "global variables" and "Static global variables."

1.2. Static local variable
before the local variable, plus the keyword static, the variable is defined as a static local variable. Let us first give an example of a static local variable, as follows:  
//example 3
#include <iostream.h>
void fn ();
void Main ()
{
  fn ();
  FN ();
  FN ();
}
void fn ()
{
  static n=10;
  cout<<n<<endl;
 n++;
}
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. A
static local variable 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.   the
static local variable has the following characteristics:
  The variable allocates memory in the global data area,  
  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;  
  Static local variables are typically initialized at the declaration and, if not explicitly initialized, are automatically initialized by the program to 0;&NBSP;
  It always resides in the global data area until the end of the program runs. But its scope is a local scope, and when the function or block of statements defining it ends, its scope ends;

1.3 Static functions
The function is defined as a static function 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:
Example 4
#include <iostream.h>
static void Fn ();//Declaration of a function
void Main ()
{
FN ();
}
VOID FN ()//define static functions
{
int n=10;
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 and no conflicts will occur;


Second, the object-oriented static keyword (the static keyword in the Class)
2.1 Static data members
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.
Example 5
#include <iostream.h>
Class Myclass
{
Public
Myclass (int a,int b,int c);
void Getsum ();
Private
int a,b,c;
static int sum;//declares a data member at rest
};
int myclass::sum=0;//to define and initialize a static data member

Myclass::myclass (int a,int b,int c)
{
this->a=a;
this->b=b;
this->c=c;
Sum+=a+b+c;
}

void Myclass::getsum ()
{
cout<< "sum=" <<Sum<<endl;
}

void Main ()
{
Myclass M (a);
M.getsum ();
Myclass N (4,5,6);
N.getsum ();
M.getsum ();

}
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, and its scope is visible when no class object is generated, 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
• 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 is allowed (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;
• Using static data members has two advantages over 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 realized. A static data member can be a private member, while a global variable cannot;

2.2 Static member functions
As with 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->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.
Example 6
#include <iostream.h>
Class Myclass
{
Public
Myclass (int a,int b,int c);
static void Getsum ();
Private
int a,b,c;
static int sum;//declares a data member at rest
};
int myclass::sum=0;//to define and initialize a static data member

Myclass::myclass (int a,int b,int c)
{
this->a=a;
this->b=b;
this->c=c;
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
cout<< "sum=" <<Sum<<endl;
}

void Main ()
{
Myclass M (a);
M.getsum ();
Myclass N (4,5,6);
N.getsum ();
Myclass::getsum ();
}
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 access each other, including static member functions to 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 using 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)
Invokes the static member function of the class.

This article from reprint, reprint address: http://www.cnblogs.com/BeyondAnyTime/archive/2012/06/08/2542315.html

Summary of the static keyword in C + + (reproduced)

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.