The way to coding--learning C + + (2): A detailed understanding of static

Source: Internet
Author: User

The Static keyword in C

1. Static local Variables

Static local variables belong to static storage, which 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 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.

For example:

voidtest_static () {Static intTemp =1; Temp++; printf ("Temp is:%d/n", Temp); }  intMainintargcChar*argv[]) {       intI=0;  for(i=0; i<=4; i++) {test_static (); } System ("Pause"); }  
voidtest_static () {Static intTemp =1; Temp++; printf ("Temp is:%d/n", Temp); }intMainintargcChar*argv[]) {         intI=0;  for(i=0; i<=4; i++) {test_static (); } System ("Pause"); }     

In fact, the static int Temp = 1 will only be executed the first time it is called.

From the above analysis, it can be seen that changing the local variable to a static variable changes its storage mode, which changes its life time.

2. Static 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.

3. 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.

The static keyword in C + + (the static keyword in the Class)

1. 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 <iostream.h>classMyclass { Public: Myclass (intAintBintc); voidgetsum (); Private:   intA,b,c; Static intSum;//declaring a static data member}; intmyclass::sum=0;//defining and initializing static data members//static int myclass::sum = 0;//Note that adding static is wrong.Myclass::myclass (intAintBintc) { This->a=A;  This->b=b;  This->c=C; Sum+=a+b+C; }  voidmyclass::getsum () {cout<<"sum="<<Sum<<Endl; }  voidMain () {Myclass M (1,2,3); M.getsum (); //cout 6Myclass N (4,5,6); N.getsum (); //coutM.getsum ();//cout} #include <iostream.h>classMyclass { Public: Myclass (intAintBintc); voidgetsum (); Private:   intA,b,c; Static intSum;//declaring a static data member}; intmyclass::sum=0;//defining and initializing static data members//static int myclass::sum = 0;//Note that adding static is wrong.Myclass::myclass (intAintBintc) { This->a=A;  This->b=b;  This->c=C; Sum+=a+b+C; }  voidmyclass::getsum () {cout<<"sum="<<Sum<<Endl; }  voidMain () {Myclass M (1,2,3); M.getsum (); //cout 6Myclass N (4,5,6); N.getsum (); //coutM.getsum ();//cout}

As you can see, 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 myclass::sum = 0; 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 following format:
Data type >< class name >::< static data member name >=< value
such as: int myclass::sum=0;


(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
M.sum = 0 or myclass::sum = 0 (But this example is not possible because he is a private variable) if the access permission of the static data member (that is, the member of public), you can refer to the static data member in the program according to the above format;

(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;

2. Static member function
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. Here is an example of a static member function.

#include <iostream.h>classMyclass { Public: Myclass (intAintBintc); Static voidGetsum (); /declaring a static member functionPrivate:   intA,b,c; Static intSum;//declaring a static data member}; intMyclass::sum =0;//defining and initializing static data membersMyclass::myclass (intAintBintc) { This->a=A;  This->b=b;  This->c=C; Sum+=a+b+c;//non-static member functions can access static data members}  //static void Myclass::getsum () {...}//plus static is wrong.voidMyclass::getsum ()//implementation of static member functions{   //cout<<a<<endl;//error code, a non-static data membercout<<"sum="<<Sum<<endl;//static functions are able to access static data members}  voidMain () {Myclass M (1,2,3);   M.getsum (); Myclass N (4,5,6);   N.getsum ();  Myclass::getsum (); } 

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: Myclass::getsum (), invokes the static member function of the class.
However, you should follow the Public,protected,private access rules as well.

The way to coding--learning C + + (2): A detailed understanding of static

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.