C++ Of static There are two uses : In process oriented programming static And in object-oriented programming static. The former applies to ordinary variables and functions , There are no classes involved ; The latter mainly explains static Function in class .

1. In process oriented design static
1.1 Static global variables
Before global variables , Add keywords static, This variable is defined as a static global variable . Let's start with 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 :
•  This variable allocates memory in the global data area ;
•  Uninitialized static global variables are automatically initialized to 0( The value of an automatic variable is random , Unless it is explicitly initialized );
•  Static global variables are visible throughout the file that declares them , And it's invisible outside 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 shown in the figure below :
Code section
Global data area
Heap area
The stack area
The general procedure consists of new The generated dynamic data is stored in the heap , The automatic variables inside the function are stored in the stack . Automatic variables generally release space as the function exits , Static data ( Even static local variables inside functions ) Also stored in the global data area . The data in the global data area does not release space due to the exit of the function . Careful readers may find this ,Example
1 In the code in “static int n; // Define static global variables ” Change it to “int n; // Define global variables ”. The program still works . You bet , Define global variables to share variables in files , But defining static global variables has the following benefits :
•  Static global variables cannot be used by other files ;
•  Variables with the same name can be defined in other files , There will be no conflict ;

You can change the above example code to the following :
//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, You will find that the above code can be compiled separately , But there was an error at runtime . Try to “static int n; // Define static global variables ” Change it to “int n; // Define global variables ”
Compile and run the program again , Experience carefully “ Global variables ” and " Static global variables " The difference between .

1.2. Static local variables
Before local variables , Add keywords static, This variable is defined as a static local variable . Let's start with 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++;
}
Usually , A variable is defined in the function body , Whenever the program runs to the statement, it allocates stack memory to the local variable . But as the program exits the function body , The system will reclaim the stack memory , Local variables fail accordingly . But sometimes we need to save the value of a variable between calls . The general idea is to define a global variable to implement . But this way , Variables no longer belong to the function itself , It's no longer just controlled by functions , Bring inconvenience to the maintenance of the program .
Static local variables can solve this problem . Static local variables are stored in the global data area , Instead of keeping it on the stack , Each time the value is held until the next call , Until the next time a new value is given .
Static local variables have the following characteristics :
•  This variable allocates memory in the global data area ;
•  Static local variables are initialized for the first time when the program executes to the object's declaration , That is, future function calls are no longer initialized ;
•  Static local variables are usually initialized at the declaration , If there is no explicit initialization , Will be automatically initialized to 0;
•  It always resides in the global data area , Until the end of the program . But its scope is local scope , When the function or statement block that defines it ends , Its scope then ends ;

1.3 Static functions
Before the return type of a function, add static keyword , Functions are defined as static functions . Static functions are different from ordinary functions , It can only be seen in the file that declares it , 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 static functions
{
  int n=10;
  cout<<n<<endl;
}
The benefits of defining static functions :
•  Static functions cannot be used by other files ;
•  Functions with the same name can be defined in other files , There will be no conflict ;

Two 、 Object oriented static keyword ( Class static keyword )
2.1 Static data members
Precede the declaration of data members in a class with keywords static, The data member is the 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();

}
It can be seen that , 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 a class . No matter how many objects of this class are defined , There is only one copy of static data members in the program , Shared access by all objects of that type . in other words , Static data members are common to all objects of this class . For multiple objects of this class , Static data members allocate memory only once , For all objects . therefore , The values of static data members are the same for each object , Its value can be updated ;

•  Static data members are stored in the global data area . Static data members are defined to allocate space , So it can't be defined in a class declaration . stay Example 5 in , sentence int Myclass::Sum=0; Is to define static data members ;
•  Static data members follow the same rules as normal data members public,protected,private Access rules ;
•  Because static data members allocate memory in the global data area , All objects belonging to this class share , therefore , It doesn't belong to a specific class object , When no class object is generated, its scope is visible , That is, when no instance of the class is generated , We can operate it ;
•  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 >
•  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 rights of static data members allow ( namely public Members of ), In the program , Reference static data members in the above format ;
•  Static data members are mainly used when all objects have the same attribute . For example, for a deposit class , The interest for each instance is the same . therefore , Interest should be set as a static data member of the deposit class . There are two advantages , First of all , No matter how many deposit class objects are defined , Interest data members share the memory allocated in the global data area , So save storage space . second , Once interest needs to change , Just change it once , Then the interest of all deposit objects has changed ;

•  Compared to global variables , There are two advantages to using static data members :
1.  Static data members do not enter the global namespace of the program , Therefore, 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 member , Global variables cannot ;

2.2 Static member functions
Like static data members , We can also create a static member function , It serves all the classes, not the specific objects of a class . Static member functions are the same as static data members , All are internal implementations of classes , Part of the class definition . A common member function usually implies a this The pointer ,this Pointer to the object of the class itself , Because ordinary member functions always belong to specific objects of a certain class . Usually ,this It's the default . Such as function fn() It's actually this->fn(). But compared to ordinary functions , Static member functions are not associated with any objects , So it doesn't have this The pointer . In this sense , It cannot access non static data members that belong to class objects , You can't 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() // Implementation of static member function
{
// cout<<a<<endl; // Error code ,a Is a non static data member
  cout<<"Sum="<<Sum<<endl;
}

void main()
{
  Myclass M(1,2,3);
  M.GetSum();
  Myclass N(4,5,6);
  N.GetSum();
  Myclass::GetSum();
}
About static member functions , It can be summed up as follows :
•  Function definitions that appear outside a class cannot specify keywords static;
•  Static members can access each other , Including static member functions, accessing static data members and accessing static member functions ;
•  Non static member functions can access static member functions and static data members at will ;
•  Static member functions cannot access non static member functions and non static data members ;
•  Because there is no this Pointer overhead , Therefore, the static member function will have a little increase in speed compared with the global function of the class ;
•  Call static member function , You can use member access operators (.) and (->) Calling static member functions for an object of a class or a pointer to an object of a class , You can also use the following format directly :
< Class name >::< Static member function name >(< Parameter table >)
Call the static member function of the class .

from:http://www.cnblogs.com/BeyondAnyTime/archive/2012/06/08/2542315.html

C++ Medium static Keyword summary of more related articles

  1. ( turn )Java Medium static Keyword parsing

    Reprint : http://www.cnblogs.com/dolphin0520/p/3799052.html One .static The purpose of keywords stay <Java Programming idea >P86 There is a passage on the page : &q ...

  2. About Java Medium static keyword

    Java Medium static keyword , It's really a key word (key word), Let's summarize its usage today , Talk about why the key . Java Medium static Key words are mainly used for memory management . Only by understanding this sentence can we compare ...

  3. Java Medium static Keyword parsing

    Java Medium static Keyword parsing static Keyword is a difficult keyword to understand when many friends write code and read code , It is also one of the knowledge points that interviewers of major companies like to ask during the interview . Let's talk about static The key ...

  4. ( turn )Java Medium static Keyword parsing

    from http://www.cnblogs.com/dolphin0520/p/3799052.html One .static The purpose of keywords stay <Java Programming idea >P86 There is a passage on the page : “sta ...

  5. ( turn )C++ Medium static Summary of keywords

    Article transferred from  http://www.cnblogs.com/BeyondAnyTime/archive/2012/06/08/2542315.html C++ Of static There are two uses : In process oriented programming ...

  6. Java Medium static Keyword parsing Reprint

    Link to the original text :http://www.cnblogs.com/dolphin0520/p/3799052.html Java Medium static Keyword parsing static Key words are encountered by many friends when writing code and reading code ...

  7. c++ About China static Keyword problem

    C++ Of static keyword C++ Of static There are two uses : In process oriented programming static And in object-oriented programming static. The former applies to ordinary variables and functions , There are no classes involved : The latter mainly explains static Function in class . ...

  8. C++ Medium static keyword ( turn )

    Original source :http://blog.csdn.net/hackbuteer1/article/details/7487694 C++ Of static There are two uses : In process oriented programming static And object-oriented programs ...

  9. Java Medium static Keyword parsing ( From Haizi )__ Why? main The method must be static Of , Because the program is executing main Method, no objects are created , So you can only access it by class name .

    Java Medium static Keyword parsing static Keyword is a difficult keyword to understand when many friends write code and read code , It is also one of the knowledge points that interviewers of major companies like to ask during the interview . Let's talk about static The key ...

Random recommendation

  1. spring springMVC

    spring It's an open source framework , To solve the problem of enterprise application development , Function as follows Purpose : Solve the complexity of enterprise application development function : Use basic javabean Instead of EJB, And provides more enterprise application functions Range : whatever java application All in all : ...

  2. Dos Learning notes (2)dos Copy of screen content

    Method 1, Select replication , Right click dos The screen => Mark => Then choose where to start copying , Drag to overlay what you want to copy , After that, OK. , press return (Enter). Method 2, Copy all , Right click dos The screen => Future generations => Then go back to ...

  3. 【dubbo】dubbo Console construction

    1.gitHub Upload and download dubbo 2.cmd Run under cd ~/dubbomvn clean install -Dmaven.test.skip 3.cd ~/dubbo/dubbo-admin mvn ...

  4. GUI User interface programming

    Java Of GUI Programming (Graphic User Interface, Graphical user interface ), It's in its abstract window toolbox (Abstract Window Toolkit,AWT) Implemented on the ,java.awt yes AWT Of ...

  5. HDU 4825 Xor Sum( classic 01 Dictionary tree + greedy )

    Xor Sum Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 132768/132768 K (Java/Others) Total ...

  6. iOS A hodgepodge of little knowledge

    from OPEN Experience 1, Print View All subviews po [[self view]recursiveDescription] 2,layoutSubviews When to call * When the view is displayed for the first time, it will be tuned ...

  7. page cache and buffer cache

    Because to optimize I/O performance , So to understand these two concepts , these two items. cache It really confused me for a long time , By looking up the information, I can understand the difference between the two , Try to say . page cache: File system level caching , What is read from the disk is stored here ...

  8. javascript Of insertBefore、insertAfter and appendChild Brief introduction

      target.insertBefore(newChild,existingChild) Parameter description :1.target: The parent node of the added node and the existing node .2.newChild: The node to be inserted .3.exis ...

  9. IIS7 http Auto jump to https

    1. Download and install URL Rewrite Module :Microsoft URL Rewrite Module 32 position :http://download.microsoft.com/download/4/9/C/49CD28DB ...

  10. z2-xcode Use

    @xcode Block naming Left navigation bar , The toolbar on the right , The next debug bar @ Shortcut key Most commonly used # Show / Hide the navigation bar :Command+ ( It's the same as a negative election Command+) # Show / Hide the toolbar :Command+Option+ ( back ...