A summary of the static keyword in C + + _c language

Source: Internet
Author: User
Tags class definition function definition

1. Static in process-oriented design
1.1 Static global variables
The variable is defined as a static global variable before the global variable, plus the keyword static. Let's first give an example of a static global variable, as follows:

Copy Code code as follows:

Example 1
#include <iostream.h>
VOID Fn ();
static int n; Defining 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 by the program to 0 (the value of the automatic variable is random unless it is explicitly initialized);
• Static global variables are visible throughout the file in which they are declared, but not outside of the file;

Static variables are allocated memory in the global data area, including the static local variables to be mentioned later.

The dynamic data generated by new in general program is stored in the heap area, and the automatic variables inside the function are stored in the stack area. Automatic variables typically release 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 of the exit of the function. Attentive readers may find that the code in Example 1 will be "static int n;" Define static global variable "to" int n; Define global variables ". The program still works. Indeed, defining a global variable enables you to share variables in a file, but there are also benefits to defining static global variables:
• Static global variables cannot be used by other files;
• Other files can be defined with the same name of the variable, does not collide;

You can change the example code above to read:

Copy Code code as follows:

Example 2
File1
#include <iostream.h>
VOID Fn ();
static int n; Defining static global Variables
void Main ()
{
n=20;
cout<<n<<endl;
FN ();
}

File2
#include <iostream.h>
extern int n;
VOID Fn ()
{
n++;
cout<<n<<endl;
}


When you compile and run Example 2, you will find that the code above can be compiled separately, but there are errors at run time. Try to "static int n;" Define static global variable "to" int n; Define Global Variables "
Compile the program again, and carefully understand the difference between "global variable" and "Static global variable".

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

Copy Code code 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 the function that allocates stack memory to the local variable whenever the program runs to that statement. However, as the program exits the function body, the system will reclaim the stack memory and the local variables should be invalidated accordingly. But sometimes we need to save the value of a variable between two calls. The usual idea is to define a global variable to implement. But in this way, the variable is no longer the function itself, is no longer only controlled by the function, to the maintenance of the program inconvenience.

Static local variables can just solve the problem. Static local variables are saved in the global data area, not on the stack, and the value is persisted to the next call until the next time the new value is assigned.

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 declaration of the object, that is, subsequent function calls are no longer initialized;
• Static local variables are typically initialized at the declaration and, if not explicitly initialized, are automatically initialized to 0 by the program;
• It always resides in the global data area until the program has finished running. But its scope is a local scope, and when the function or statement block that defines it ends, its scope ends;

1.3 Static functions
By adding the static keyword before the return type of the function, the function is defined as a static function. A static function, unlike a normal function, can only be visible in the file in which it is declared and cannot be used by other files.

Examples of static functions:

Copy Code code as follows:

Example 4
#include <iostream.h>
static void Fn ();
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, and no conflict occurs;

Second, object-oriented static keywords (static keywords in a class)
2.1 Static data members
Add a keyword static before the declaration of a data member within a class, which is a static data member within a class. Give an example of a static data member first.

Copy Code code as follows:

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;//declares a member of a statically data
};
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 you can see, 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, static data members have only one copy in the program, and access is shared by all objects of that type. In other words, static data members are common to all objects of the class. For multiple objects of the class, static data members are allocated only once in memory for all objects to share. Therefore, the value of the static data member is the same for each object, and its value can be updated;

• Static data members are stored in the global data area. Static data member definitions are allocated space, so they cannot be defined in class declarations. In Example 5, the statement int myclass::sum=0 is defined as a static data member;

• Static data members comply with PUBLIC,PROTECTED,PRIVATE access rules like regular data members;

• Because static data members allocate memory in the global data area and are shared by all objects of this class, it is not part of a particular class object and is visible when no class object is generated, that is, we can manipulate it without producing an instance of the class;

• Static data member initialization differs from general data member initialization. The format for 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 permission of 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;

• Static data members are mainly used when each object has 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 benefits, first, that the interest data members share the memory allocated in the global data area, regardless of the number of deposit objects defined, thus saving storage space. Second, once the interest needs to change, as long as the change, then all the deposit of the object of interest all change over;

• There are two advantages to using static data members compared to global variables:
1. Static data members have no access to the global namespace of the program, so there is no possibility of conflict with other global names in the program;
2. Can realize information hiding. Static data members can be private members, and global variables cannot;

2.2 Static member functions
As with static data members, we can also create a static member function that serves all of the class's services rather than the specific object of a particular class. Static member functions, like static data members, are internal implementations of a class and are part of the class definition. Ordinary member functions implicitly imply a this pointer, the this pointer points to the object itself of the class, because the ordinary member function is always specific to the specific object of a class. Typically, this is the default. such as the function fn () is actually THIS->FN (). However, a static member function does not have the this pointer because it is not associated with any object, as opposed to a normal function. In this sense, it does not have access to non-static data members belonging to the class object, nor does it have access to non-static member functions, and it can only invoke the rest of the static member functions. Here's an example of a static member function.

Copy Code code as follows:

Example 6
#include <iostream.h>
Class Myclass
{
Public
Myclass (int a,int b,int c);
static void Getsum ();/declaring a statically member function
Private
int a,b,c;
static int sum;//declares a member of a statically data
};
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
}

Implementation of void Myclass::getsum ()//static member function
{
cout<<a<<endl; Error code, 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 ();
}


for static member functions, you can summarize the following points:
• A function definition that appears outside the class body cannot specify a keyword static;
• Static members can access each other, including static member functions to access static data members and access to static member functions;
• Non-static member functions can access static member functions and static data members arbitrarily;
• Static member functions cannot access non-static member functions and non-static data members;
• Because there is no extra overhead for this pointer, static member functions have a slight increase in speed compared to the global functions of a class;
• Call static member functions, which can be accessed using the member access operator (.) and (->) call static member functions for objects of a class or pointers to class objects, or you can use the following format directly:
Class name >::< static member function name > (parameter table)
Calls a static member function of a class.

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.