C + + series: static

Source: Internet
Author: User
Tags class definition

The static of C + + has two usages: static in process-oriented programming and static in object-oriented programming. The former applies to ordinary variables and functions, and does not involve classes; the latter mainly describes the role of static in classes.
First, the static in the process design oriented
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:
[CPP] View plain copy
#include <iostream>
using namespace Std;

static int n; Defining static global Variables

VOID Fn ()
{
n++;
cout<<n<<endl;
}

int main (void)
{
n = 20;
cout<<n<<endl;
FN ();
return 0;
}
Static global variables have the following characteristics:
The 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);
A static global variable is visible in the entire file that declares it, and is invisible outside of 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 as follows:
Code Area
Global Data area
Heap Area
Stack area
The dynamic data generated by new in the general program is stored 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


[CPP] View plain copy
static int n; Defining static global Variables
Switch

[CPP] View plain copy
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 files, but there are also the following benefits of 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:
[CPP] View plain copy
File1
#include <iostream>
using namespace Std;

VOID Fn ();
static int n; Defining static global Variables

int main (void)
{
n = 20;
cout<<n<<endl;
FN ();
return 0;
}

File2
#include <iostream>
using namespace Std;

extern int n;

VOID Fn ()
{
n++;
cout<<n<<endl;
}
Compile and run the program, and you will see that the code above can be compiled separately, but there is an error at run time. Try to

[CPP] View plain copy
static int n; Defining static global Variables
Switch

[CPP] View plain copy
int n; Defining Global Variables
Compile and run the program again, carefully understand the difference between global variables and static global variables.
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:
[CPP] View plain copy
#include <iostream>
using namespace Std;

VOID Fn ();

int main (void)
{
FN ();
FN ();
FN ();
return 0;
}

VOID Fn ()
{
static int 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 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 usually initialized at the declaration, if not explicitly initialized, the program is automatically initialized to 0;
(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:
[CPP] View plain copy
#include <iostream>
using namespace Std;

static void Fn (); declaring static functions

int main (void)
{
FN ();
return 0;
}

VOID FN ()//define static functions
{
int n = 10;
cout<<n<<endl;
}
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;
Second, the object-oriented static keyword (the static keyword in 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.
[CPP] View plain copy
#include <iostream>
using namespace Std;

Class Myclass
{
Private
int A, b, C;
static int sum; Declaring a static data member
Public
Myclass (int A, int b, int c);
void Getsum ();
};

int myclass::sum = 0; Defining and initializing 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;
}

int main (void)
{
Myclass M (1, 2, 3);
M.getsum ();
Myclass N (4, 5, 6);
N.getsum ();
M.getsum ();
return 0;
}
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 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;
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;
Static data members comply with PUBLIC,PROTECTED,PRIVATE access rules like normal data members;
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-&GT;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.

[CPP] View plain copy
#include <iostream>
using namespace Std;

Class Myclass
{
Private
int A, b, C;
static int sum; Declaring a static data member
Public
Myclass (int A, int b, int c);
static void Getsum (); Declaring a static member function
};

int myclass::sum = 0; Defining and initializing 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 member
cout<< "sum=" <<sum<<endl;
}

int main (void)
{
Myclass M (1, 2, 3);
M.getsum ();
Myclass N (4, 5, 6);
N.getsum ();
Myclass::getsum ();
return 0;
}
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 be accessed from one another, including static member functions that access static data members and access static member functions;
Static member functions and static data members can be accessed arbitrarily by non-static member functions;
Static member functions cannot access non-static member functions and non-static data members;
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.

C + + series: 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.