Use of static

Source: Internet
Author: User

Reference:

Static usage Detailed http://www.cnblogs.com/heyonggang/p/3198431.html

static function and normal function http://blog.163.com/sunshine_linting/blog/static/44893323201191294825184/

I. Process-oriented programming

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;  //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:

    1. The variable allocates memory in the global data area ;
    2. Uninitialized static global variables are automatically initialized by the program to 0 (the value of the automatic variable declared in the function body is random, unless it is explicitly initialized, and the automatic variable declared outside the function body is initialized to 0);
    3. A static global variable is visible in the entire file that declares it, and is invisible outside of the file ;
    4. 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//low address global data area heap area//high address

The general program stores the newly generated dynamic data 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 . Careful readers may find that the code in Example 1 will
static int n; Defining static global Variables
Switch
int n; Defining Global Variables
The program is still functioning normally.
It is true that defining global variables allows for the sharing of variables in a file.

However, there are several benefits to 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:

  1. Example 2//file1
  2. #include <iostream.h>
  3.   VOID Fn ();
  4.   static int n; //define static global variables
  5.   void Main ()
  6. {n=20;
  7. cout<<n<<endl;
  8. FN ();
  9. }
  10.   File2
  11. #include <iostream.h>
  12.   extern int n;
  13.   VOID Fn ()
  14. {n++;
  15. cout<<n<<endl;
  16. }

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 to
static int n; Defining static global Variables
Switch
int n; Defining Global Variables
Compile and run the program again, carefully understand the difference between global variables and static global variables.
Note: The difference between global variables and global static variables
1) Global variables are global variables that are not explicitly decorated with static, but global variables are dynamic by default , scope is the entire project, global variables are defined within one file, and global variables are available in another file through the declaration of the extern global variable name.
2) A global static variable is a global variable that is explicitly modified with static, the scope is the file where it is located , and the other file is not used with the extern declaration.
  

2. Static local Variables
Before a local variable, the variable is defined as a static local variable, plus the keyword static.
Let's first give an example of a static local variable, as follows:

    1. Example 3
    2. #include <iostream.h>
    3.   VOID Fn ();
    4.   void Main ()
    5. {fn ();
    6. FN ();
    7. FN ();
    8. }
    9.   VOID Fn ()
    10. { static int n=10;
    11. cout<<n<<endl;
    12. n++;
    13. }

Operation Result:

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.
Static local variables 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.

static local variables have the following characteristics :

    1. The variable allocates memory in the global data area;
    2. A 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;
    3. Static local variables are typically initialized at the declaration and, if not explicitly initialized, are automatically initialized to 0 by the program;
    4. It always resides in the global data area until the program finishes running. But its scope is local scope, when the function or statement block that defines it ends, its scope ends;

3. Static function
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:

    1. Example 4
    2. #include <iostream.h>
    3.  static void Fn (); Declaring static functions
    4.  void Main ()
    5. {
    6. FN ();
    7. }
    8.  VOID fn ()//define static functions
    9. { int n=10;
    10. cout<<n<<endl;
    11. }

Benefits of defining static functions:

    •   Static functions cannot be used by other files;
    •   Other files can define a function of the same name, and no conflict will occur;

Two. Object-oriented Programming
( static keyword in class )

public static data members can be accessed externally by the class, protected, or private static data members can only be accessed internally by the class.


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.

  1. Example 5
  2. #include <iostream.h>
  3. Class Myclass
  4. {
  5. Public
  6. Myclass (int A,int b,int c);
  7. void Getsum ();
  8. Private
  9. int a,b,c;
  10. static int Sum; Declaring a static data member
  11. };
  12. int myclass::sum=0; //define and initialize static data members
  13. Myclass::myclass (int A,int b,int c)
  14. { this->a=a;
  15. this->b=b;
  16. this->c=c;
  17. Sum+=a+b+c;}
  18. void Myclass::getsum ()
  19. {cout<<"sum=" <<Sum<<endl;
  20. }
  21. void Main ()
  22. {Myclass M (n/a);
  23. M.getsum ();
  24. Myclass N (4,5,6);
  25. N.getsum ();
  26. M.getsum ();}

Operation Result:

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. Therefore, the value of the static data member is the same for each object, and its value can be updated;
    2. 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;
    3. Static data members comply with PUBLIC,PROTECTED,PRIVATE access rules like normal data members;
    4. 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, its scope is visible when no class object is produced, 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 >

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

There are two advantages to using static data members compared to global variables:

    • 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;
    • Information hiding can be implemented. A static data member can be a private member, while a global variable cannot;

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.
  

  1. Example 6
  2. #include <iostream.h>
  3.   Class Myclass
  4. {Public:
  5. Myclass (int A,int b,int c);
  6.   static void Getsum ();
  7.   Private
  8.   int a,b,c;
  9.   static int Sum; Declaring a static data member
  10. };
  11.   int myclass::sum=0; //define and initialize static data members
  12. Myclass::myclass (int A,int b,int c)
  13. { this->a=a;
  14.   this->b=b;
  15.   this->c=c;
  16. Sum+=a+b+c; //non-static member functions can access static data members
  17. }
  18.   void Myclass::getsum () //static member function implementation
  19. {//cout<<a<<endl;//error code, a non-static data member
  20. cout<<"sum=" <<Sum<<endl;
  21. }
  22.   void Main ()
  23. {Myclass M (n/a);
  24. M.getsum ();
  25. Myclass N (4,5,6);
  26. N.getsum ();
  27. Myclass::getsum ();
  28. }

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 one another, including static member functions that access static data members and access 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;
    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;

Call a 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 >)
Invokes the static member function of the class.
Role
Static variable declarator. In declaring its program block, the subroutine block or function is valid internally, the value remains, the memory space is allocated throughout the program, and the compiler defaults to 0.
is a commonly used modifier in C + +, which is used to control how variables are stored and visible.

Why are you introducing static?
A variable defined inside a function, when the program executes to its definition, the compiler allocates space on the stack, and you know that the space allocated by the function on the stack is freed at the end of the function execution (note: The allocated space on the stack ends after the function executes) this creates a problem: What if you want to save the value of this variable in a function to the next call? The easiest way to think of is to define a global variable, but there are many drawbacks to defining a global variable, and the most obvious disadvantage is that it destroys the scope of access to the variable (the variable defined in this function is not only controlled by this function).

When do you use static?
A data object is required to serve the entire class rather than an object, while at the same time trying not to break the encapsulation of the class, which requires that the member be hidden inside the class and not visible externally.

The internal mechanism of static
A static data member must exist at the beginning of a program run. Because a function is called in a program run, a static data member cannot allocate space and initialization within any function.
In this way, its spatial allocation has three possible places, one is the header file as the outer interface of the class, there is the class declaration, and the second is the inner implementation of the class definition, there is the member function definition of the class, and the third is the global data declaration and definition in front of the main () function of the application.
Static data members are actually allocated space, so they cannot be defined in the declaration of a class (only data members can be declared). A class declaration declares only "dimensions and specifications" of a class and does not actually allocate memory, so it is wrong to write a definition in a class declaration. It also cannot be defined externally in the header file for the class declaration, because that would cause duplicate definitions in multiple source files that use the class.
Static is introduced to tell the compiler to store variables in the program's static storage instead of on-stack space, static
Data members are initialized sequentially in the order in which they are defined, and when static members are nested, ensure that the nested members are initialized. The order of elimination is the inverse order of the initialization.

The advantages of static
Can save memory because it is public to all objects, so for multiple objects, static data members are stored only one place for all objects to be shared. The value of a static data member is the same for each object, but its value can be updated. As long as the value of the static data member is updated once, it is guaranteed that all objects access the same value after the update, which can improve time efficiency.

Application format
When you reference a static data member, the following format is used:
< class name >::< static member name >
If the access permission for a static data member is allowed (that is, a member of public), the static data member can be referenced in the program in the format described above.
Precautions
(1) A static member function of a class is an object of the entire class rather than a class, so it does not have the this pointer, which causes it to access only the static data and static member functions of the class.
(2) A static member function cannot be defined as a virtual function.
(3) because the static member is declared in the class, the operation is outside, so it takes the address operation, it is somewhat special, the variable address is a pointer to its data type, the function address type is a "nonmember function pointer".
(4) Since the static member function does not have this pointer, it is almost identical to the nonmember function, resulting in an unexpected benefit: being a callback function allows us to combine the C + + and c-based X window systems, It is also successfully applied to the thread function.
(5) Static does not increase the space-time overhead of the program, but she also shortens the subclass's access time to the static members of the parent class, saving the memory space of the child class.
(6) static data members in the < definition or description > before adding the keyword static.
(7) A static data member is stored statically, so it must be initialized.
(8) Static member initialization differs from general data member initialization:

    • Initialization is performed outside of the class body, and the front is not static, so as not to be confused with the general static variables or objects;
    • Initialization without the access control of the member Private,public and so on;
    • The scope operator is used when initializing to indicate the class to which it belongs;

So we derive the format of the static data member initialization:


< data type >< class name >::< static data member name >=< value >
  

(9) To prevent the effect of the parent class, you can define a static variable in the subclass that is the same as the parent class to mask the effect of the parent class. Here's one thing to note: we say that static members are shared by the parent and subclass, but we have statically defined static members, does that cause errors? No, our compiler uses a neat trick: name-mangling is used to generate unique flags. The questions that often appear in the written interview of each communication company are the function and function of static.

the static function in C
Category

static function intrinsics and external functions
When a source program consists of multiple source files, the C language is divided into internal functions and external functions according to whether the function can be called by functions in other source files.
intrinsic Functions
(also called 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 an intrinsic function.
To define an intrinsic 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.
External functions
Definition of an external function: when defining a function, if the keyword "static" is not added, or the keyword "extern" indicates that the function is an external function:
[extern] Function type function name (function parameter table)
{......}
When you call an external function, you need to describe it:
[extern] Function type function name (parameter type table) [, Function name 2 (parameter Type table 2) ...] ;
[Case] External function application.
(1) File MAINF.C
Main ()
{extern void input (...), process (...), output (...);
Input (...); Process (...); Output (...);
}
(2) file subf1.c
......
extern void input (...)/* Define external function */
{......}
(3) file subf2.c
......
extern void process (...)/* Define external function */
{......}
(4) File subf3.c
......
extern void output (...)/* Define external function */
{......}

Static in Java

function

Sometimes you want to define a class member so that its use is completely independent of any object of that class. Typically, a class member must be accessed through the object of its class, but it can create a member that can be used by itself without referencing a particular instance. Such a member can be created by adding the keyword static (static) before the member's declaration. If a member is declared static, it is able to be accessed before any object of its class is created, without having to reference any object. You can declare methods and variables as static. The most common example of a static member is main (). Because main () must be called when the program starts executing, it is declared as static.
A variable that is declared static is called a statically variable or a class variable. Static variables can be referenced directly through the class name, or static variables can be referenced through the instance name, but it is preferable to use the former because the latter is prone to confusing static and generic variables. A static variable is associated with a class, and all instances of the class share a static variable.
A method that is declared static is referred to as a stationary method or a class method. Static methods can call static methods directly, access static variables, but cannot directly access instance variables and instance methods. The This keyword cannot be used in a static method because the static method does not belong to any one instance. Static methods cannot be overridden by a static method of a quilt class.
Example
If you need to initialize your static variable with a calculation, you can declare a static block that executes only once when the class is loaded. The following example shows a class that has a static method, some static variables, and a static initialization block:

  1. Demonstrate static Variables,methods,and blocks.
  2.   Class Usestatic {
  3.   static int a = 3;
  4.   static int B;
  5.   static void Meth (int x) {
  6. System.out.println ("x =" + x);
  7. System.out.println ("a =" + a);
  8. System.out.println ("b =" + B);
  9. }
  10.   static {
  11. System.out.println ("Static block initialized.");
  12. b = A * 4;
  13. }
  14.   Public static void Main (String args[]) {
  15. Meth (42);
  16. }
  17. }

Once the Usestatic class is loaded, all static statements are run. First, A is set to 3, then the static block executes (prints a message), and finally, B is initialized to a*4 or 12. Then call Main (), main () call meth () and pass the value 42 to X. The 3 println () statements refer to two static variables A and B, and the local variable x.
Note: Referencing any instance variable in a static method is illegal.
The following is the output of the program:
Static block initialized.
x = 42
A = 3

b = 12

1. To use a static data member must allocate space and initialization before the main () program runs. With static member functions, you can then actually create any object before you initialize a proprietary static data member. A static member is not associated with any particular object of the class. 2. Static statics and static storage classes are two concepts, a theory and a class, a discussion of the location of the memory space and scope limits. So you distinguish between static and static members.

Use of static

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.