Completely understand the static keyword

Source: Internet
Author: User

Static is also a keyword we often use, there are many uses for static, and static has different meanings in process-oriented and object-oriented programming. Before always remember, so, I have obsessive-compulsive disorder again, must understand it!!!


I. The static keyword for process programming 1. Static global variable static global variable:
C++test.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <iostream> #include <string>using namespace std;static int S_test;int nons_ Test;int _tmain (int argc, _tchar* argv[]) {//static global variables are initialized by default to 0cout<< "static:" <<s_test<<endl;// The non-static global variable default initialization is also 0, but if it is a local non-static variable, the direct error in VS cannot be compiled cout<< "non-static:" <<nons_test<<endl;system (" Pause "); return 0;}

Results: static:0
non-static:0
Please press any key to continue ...

When we run the program, the memory is divided into code area, global data area, heap area, and stack area. The normal temporary variable auto and so on the stack area, the life cycle is the function end, and the new object is generally in the heap area, the declaration period is controlled by us, new when the start, delete when the end. The global data area holds global variables and static variables, and their life cycle is the entire program's running cycle.
The difference between using a static global variable and using a normal global variable: 1) If the global variable is in the header file, or both use and definition are in the same file, the static global variable and the normal global variable are the same.
The StaticTest.h header file defines the static global variables and the normal global variable static int static_num = 20;int Nonstatic_num = 30;

C++test.cpp: Defines the entry point of the console application. Global variables There is no difference between a header file or this file. Include "stdafx.h" #include <iostream> #include <string> #include "StaticTest.h" #include "StaticTest1.h" using namespace std;int _tmain (int argc, _tchar* argv[]) {//If the static variable is in the header file or in this file, you can access the static global variable cout << "Static:" <<static_num<<endl;//if the static variable is in the header file or in this file, you can access the non-static global variable cout<< "non-static:" < <nonstatic_num<<endl;system ("pause"); return 0;}

Results: static:20
Non-static:30
Please press any key to continue ...


2) If the global variable is in a. cpp file, the normal global variable is globally visible, that is, other files are visible, but when used, the extern keyword is added to other files. And if not added, in this file again declare the same name of the variable, will be error. However, using static global variables can solve this problem, static global variables are not visible in other files, we do not need to pay attention to the global variables in other files, there is no use of the same name global variables problem!
. H file #ifndef __statictest1_h_#define __statictest1_h_#pragma onceclass statictest1{public:statictest1 (void); Virtual ~statictest1 (void);}; #endif//.cpp file # include "stdafx.h" #include "StaticTest1.h"//define global variables in. cpp files static int static_test = 10;int nonstatic_ Test = 20; Statictest1::statictest1 (void) {}statictest1::~statictest1 (void) {}
Main function File:
C++test.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <iostream> #include "StaticTest1.h" using namespace Std;extern int nonstatic_test; extern int static_test;int _tmain (int argc, _tchar* argv[]) {//If the static variable is in another. cpp file, the static global variable cannot be accessed, even if the extern declaration is used in this file//cout << "Static:" <<static_test<<endl;//if the static variable is in another. cpp file, you can access the non-static global variable, but use the extern declaration in this file cout<< " Non-static: "<<nonstatic_test<<endl;system (" pause "); return 0;}

When extern is not added, the static global variable is undefined, even if an extern declaration is added: c++test2.obj:error LNK2001: unresolved external symbol "int static_test" ([email protected]@ 3HA)
1&GT: Fatal error lnk1120:1 an unresolved external command


For static global variables, there are three points to note: 1) If the static global variable is uninitialized, it will be initialized to 0 instead of the static global variable, note the global variable, and the initial value is 0. (Non-static non-global variables if uninitialized in VS will directly error) 2) The static global variable is not in the global data area, so the lifetime of the variable is the whole program's running period. (The lifetime of a local static variable is also the entire program's operating period) 3) static global variables are visible in the file declared by the variable, but not in other files.
About Global variables: if we put the global variables directly in the header file, the variables are introduced into each file as the header file is introduced. Sometimes this is something we don't want to see, so the other way is to put the global variable in the. cpp file so that the global variable is not being introduced everywhere with. h files, not globally visible. However, this variable is still a global variable, in order to use this variable in another file, it is necessary to use the extern keyword in this file to declare it. If you do not declare, you will get a case where the variable is not declared. If you define a variable of the same name directly in this variable, there will be a flush definition, which is what we do not want to see, if the global variable is only useful in this file, then use the static global variable directly.

2. Static local VariablesLocal variables, which are variables stored in the stack space, are initialized when the function is called, and at the end of the function call, the lifetime of the local variable ends and is destroyed. And sometimes we need to save the variables between the two call functions, the simplest idea is to use a global variable, but this variable is not part of the function itself, but the global visibility, does not conform to the principle of local, maintenance caused inconvenience. and static local variables just can solve this problem. Static local variables are stored in the global data area, are not destroyed by the end of the function, and in other functions, static local variables are not visible, just meet our needs!
Let's look at an example:

C++test.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <iostream> #include <string> #include <vector>using namespace std;void TestFunc () {///defines a static local variable, but this variable is initialized only the first time, the static int static_num = 10;//is no longer initialized when called again, but the normal local variable is initialized each time int nonstatic_ num = 10;static_num++;nonstatic_num++;cout<< "non_static:" <<nonstatic_num<< "  Static:" < <static_num<<endl;} int _tmain (int argc, _tchar* argv[]) {//call 10 times the function for (int i = 0; i <; i++) TestFunc (); System ("pause"); return 0;}

Results:

Non_static:11 static:11
Non_static:11 Static:12
Non_static:11 static:13
Non_static:11 static:14
Non_static:11 static:15
Non_static:11 static:16
Non_static:11 static:17
Non_static:11 static:18
Non_static:11 static:19
Non_static:11 static:20
Please press any key to continue ...


As we can see from the above results, the function is called 10 times, and the non-static variable is initialized each time, thus the result is unchanged. Static variables are initialized only once, so each result is 1 larger than the previous one.


Some points to note about local static variables:

1) Local static variables also allocate memory in the global data area and are not destroyed by the end of the function call.

2) A local static variable is initialized when it is first called to the variable, and then is not initialized again when it is called again. and local static variables are typically initialized at the declaration, and if not initialized, the default is initialized to 0

3) The life cycle of a local static variable is declared at the end of the program, but its scope is local, only within the function, does not destroy the principle of locality.


3. Static function functions are globally visible by default, and if we want a function to be visible only in this file, you can declare it as a static function. This is similar to a static global variable. An example:
Statictest.h#include <iostream>using namespace Std;void normalfunctest (); static void Staticfunctest ();

Statictest.cpp#include "stdafx.h" #include "StaticTest.h" void Normalfunctest () {cout<< "Normal func!" <<endl;} static void Staticfunctest () {cout<< "Static func!" <<endl;}

C++test.cpp: Defines the entry point of the console application. Main function # include "stdafx.h" #include <iostream> #include "StaticTest.h" using namespace std;int _tmain (int argc, _ tchar* argv[]) {normalfunctest (); Staticfunctest (); System ("pause"); return 0;}
In this example, two functions are defined in another file, one is a normal function and the other is a static function. Compile, the following error will appear:
\vs2012\vs12\vc\include\xlocnum (155): Error C2129: static function "void staticfunctest (void)" declared but not defined

That is, the compiler sees only the declarations in the. h file, but does not see the implementation in the. cpp file. In this way, the purpose of static is achieved! However, if the implementation of the function is placed in the. h, then, whether it is static or not, it can be used.

Two. Static keyword in object-oriented programming 1. Data members in a class, members can also be declared as static data members, and in object-oriented programming, the static keyword has new functionality. Let's start with an example:
C++test.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <iostream>using namespace Std;class statictest{private://Here is a declaration, declaring a static member variable static int count;int id;public:statictest (int i): ID (i) {count++;} void Show () {cout<< "ID:" <<ID<<ENDL;} static void Showcount () {cout<< "Count:" <<count<<endl;}};/ /define and initialize static member variables outside of the class, you cannot define an int statictest::count = 0;int _tmain (int argc, _tchar* argv[]) {statictest) in a class declaration because you need to allocate space for the definition Test1 (1); Statictest test2 (2); test1. Show (); test2. Show (); Statictest::showcount (); System ("pause"); return 0;}

Results: Id:1
Id:2
Count:2
Please press any key to continue ...

There are a few things about static member variables: 1) Static member variables are only one copy of a class, shared by all objects of that class, and static data members are allocated only once memory. A non-static member variable is one copy of each object. 2) static member variables follow public,private,protected access rules 3) static data members allocate memory in the global data area, belong to all object shares of this class, but it does not belong to any one object, so static member variables can be used even if no object is produced. 4)static member variables are very special initialization, not directly like ordinary member variables in the class to give the initial value, and not directly initialized as non-member variables, static member variables need to be declared in the definition of the class, and then outside the class, with the < type >< class name >::< variable name > = < value > format to initialize. As in the above example: int statictest::count = 0;5) There are two ways to access static member variables, one is the same as normal member variable access,< object name >.< static data member >. The other is a static member variable-specific way < class name >::< static data member >



2. Static member functions

Or the above example, add a part of the function:

C++test.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <iostream>using namespace Std;class statictest{private://Here is a declaration, declaring a static member variable static int count;int id;public:statictest (int i): ID (i) {count++;} void Show () {///But non-static member functions can access static member functions and Variables cout<< "ID:" <<id<< "  Count:" <<COUNT<<ENDL;} The static void Showcount () {////member function does not have access to non-static members, not static member functions! cout<< "ID:" <<id<<endl;     Error C2597: Illegal reference to non-static member "Statictest::id"//show ();:                    error C2352: "statictest::show": illegal invocation of non-static member function cout<< " Count: "<<count<<endl;}};/ /define and initialize static member variables outside of the class, you cannot define an int statictest::count = 0;int _tmain (int argc, _tchar* argv[]) {statictest) in a class declaration because you need to allocate space for the definition Test1 (1); Statictest test2 (2); test1. Show (); test2. Show (); Statictest::showcount (); System ("pause"); return 0;}

Results:

Id:1 Count:2
Id:2 Count:2
Count:2
Please press any key to continue ...


Note about static member functions:

1) static member functions can access static member functions and static member variables. However, static member functions cannot access ordinary member variables and ordinary member functions. (because the static member function does not have this pointer, it belongs to the shared)

2) non-static member functions can access static member variables and static member functions.

3) static member functions defined outside the class cannot be static and can be declared with the same static as the normal member function.

4) Static member functions are consistent with the calling rules of static member variables, and do not require an object to be called. You can use the normal method, or you can use the class name:: Call.






Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Completely understand the static keyword

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.