A summary of the static keyword in C++

  • 2020-04-02 01:38:28
  • OfStack

1. Static in process oriented design
1.1 static global variables
A global variable is defined as a static global variable by adding the keyword static in front of it. Let's first take an example of a static global variable, as follows:


//Example 1
#include <iostream.h>
void fn();
static int n; //Define 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 & # 8226; This variable allocates memory in the global data area;
The & # 8226; An uninitialized static global variable is automatically initialized to 0 (the value of the automatic variable is random unless it is explicitly initialized).
The & # 8226; A static global variable is declared to be visible to its entire file and not to be visible outside the file.

Static variables allocate memory in the global data area, including the static local variables mentioned later.

The dynamic data generated by new for general programs is stored in the heap, and the automatic variables inside the function are stored in the stack. Automatic variables typically free up space as the function exits, and static data (even static local variables within the function) is stored in the global data area. The data in the global data area does not free up space because the function exits. An observant reader might notice that the code in Example 1 contains "static int n; // define the static global variable "to" int n; // define global variables ". The program still works fine. Sure, defining global variables allows you to share variables in files, but defining static global variables has the following benefits:
The & # 8226; Static global variables cannot be used by other files;
The & # 8226; Variables with the same name can be defined in other files without conflicts.

You can change the above sample code to look like this:


//Example 2
//File1
#include <iostream.h>
void fn();
static int n; //Define 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, and you will see that the above code can be compiled separately, but there is an error at run time. Try "static int n;" // define the static global variable "to" int n; // define global variables"
Compile and run the program again, and notice the difference between "global variables" and "static global variables."

1.2. Static local variables
Before a local variable, add the keyword static, and the variable is defined as a static local variable. Let's first take 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 a function, and stack memory is allocated to that local variable whenever the program runs to that statement. However, as the program exits the function body, the system will withdraw the stack memory and local variables will be invalidated accordingly. But sometimes we need to save the value of the variable between calls. The general idea is to define a global variable to implement. But as a result, variables no longer belong to the function itself, and are no longer only controlled by the function, bringing inconvenience to the maintenance of the program.

Static local variables can solve this problem. Static local variables are stored in the global data area rather than on the stack, with each value held until the next call until the next assignment.

Static local variables have the following characteristics:
The & # 8226; This variable allocates memory in the global data area;
The & # 8226; Static local variables are initialized for the first time when the program executes to the declaration of the object, that is, subsequent function calls are not initialized;
The & # 8226; Static local variables are generally initialized in the declaration, if not explicitly initialized, will be automatically initialized to 0 by the program;
The & # 8226; It stays in the global data area until the program runs. But its scope is local scope, when the function or statement block that defines it ends, its scope ends;

1.3 static function
A function is defined as static by adding the static keyword to its return type. Unlike normal functions, static functions are visible only in the file in which they are declared and cannot be used by other files.

Examples of static functions:


//Example 4
#include <iostream.h>
static void fn();//Declare static functions
void main()
{
   fn();
}
void fn()//Define a static function
{
   int n=10;
   cout<<n<<endl;
}

Benefits of defining static functions:
The & # 8226; Static functions cannot be used by other files;
The & # 8226; Functions with the same name can be defined in other files without conflicts.

2. Object oriented static keyword (static keyword in class)
2.1 static data members
When the keyword static is added before the declaration of a data member in a class, the data member is a static data member in the class. Let's start with an example of a static data member.


//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;//Declare static data members
};
int Myclass::Sum=0;//Define and initialize static data members
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(1,2,3);
   M.GetSum();
   Myclass N(4,5,6);
   N.GetSum();
   M.GetSum();
}

As can be seen, static data members have the following characteristics:
The & # 8226; For non-static data members, each class object has its own copy. Static data members are treated as members of a class. No matter how many objects are defined in the class, static data members have only one copy in the program, Shared by all objects of that type. That is, static data members are common to all objects of the class. For multiple objects of this class, the static data member allocates memory only once and is Shared by all objects. Therefore, the value of the static data member is the same for each object, and its value can be updated;

The & # 8226; Static data members are stored in the global data area. Static data members are defined to allocate space, so they cannot be defined in a class declaration. In Example 5, the statement int Myclass::Sum=0; Is to define static data members;

The & # 8226; Static data members follow public,protected, and private access rules just like normal data members;

The & # 8226; Because the static data member allocates memory in the global data area, all objects belonging to this class share, so, it does not belong to the specific class object, when there is no class object, its scope is visible, that is, when there is no class instance, we can operate it;

The & # 8226; Static data member initialization is different from general data member initialization. The format of static data member initialization is:
< data type > < class name > :: < static data member name > = < value >

The & # 8226; Static data members of a class have two forms of access:
< 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.

The & # 8226; Static data members are mainly used when each object has the same property. For example, for a savings class, the 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. First, no matter 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, as long as it is changed once, the interest of all deposit objects is changed;

The & # 8226; There are two advantages to using static data members over global variables:
1. Static data members do not enter the global namespace of the program, so there is no possibility of conflicts with other global names in the program;
2. Information hiding can be realized. Static data members can be private, but global variables cannot;

2.2 static member functions
Like static data members, we can create a static member function that serves the entire class rather than the specific object of a class. Static member functions, like static data members, are internal implementations of a class and are part of the class definition. Ordinary member functions generally imply an this pointer to the object of the class itself, because ordinary member functions are always specific to specific objects of a class. Normally, this is the default. The function fn() is actually this- > Fn (). But in contrast to normal functions, static member functions do not have this pointer because they are not associated with any object. In this sense, it cannot access non-static data members that belong to class objects, nor can it access non-static member functions, it can only call the rest of the static member functions. Here's 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();/ Declare static member functions 
private:
   int a,b,c;
   static int Sum;//Declare static data members
};
int Myclass::Sum=0;//Define and initialize static data members
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 members 
   cout<<"Sum="<<Sum<<endl;
}
void main()
{
   Myclass M(1,2,3);
   M.GetSum();
   Myclass N(4,5,6);
   N.GetSum();
   Myclass::GetSum();
}

The static member function can be summarized as the following:
The & # 8226; Function definitions that appear outside a class cannot specify the keyword static;
The & # 8226; Static members can access each other, including static member function access static data members and static member function access;
The & # 8226; Non-static member function can access static member function and static data member arbitrarily;
The & # 8226; Static member functions cannot access non-static member functions and non-static data members;
The & # 8226; Since there is no overhead associated with this pointer, the static member function is slightly faster than the global function of the class.
The & # 8226; Call the static member function, and you can use the member access operators (.) and (-) > ) call a static member function for an object of a class or a pointer to a class object, or directly use the following format:
< class name > :: < static member function name > (< parameter table >)
Calls the static member function of the class.


Related articles: