Static member variables and static member functions in C + + (process-oriented && object-oriented)

Source: Internet
Author: User
Tags class definition

Data members can be divided into static variables, non-static variables, two kinds.

Static member: A member in a static class joins the static modifier, which is a statically member. You can access this static member directly using the class name + static member name, because static members exist in memory, non-static members need to be instantiated to allocate memory, so static members cannot access non-static members: Because static members exist in memory, non-static members can access static members of the class directly.


non-static member: All members that do not have static members are nonstatic, and when the class is instantiated, it can be accessed by instantiating the class name. The lifetime of a non-static member is determined by the lifetime of the class. Static members, however, do not have the concept of a lifetime because static members always reside in the content.

You can also include static and non-static members in a class, as well as static constructors and non-static constructors.

Summed up in two ways, the first aspect is mainly relative to the process , that is, in this respect the class is not involved, the second aspect of the object-oriented, the main explanation of the role of static in the class.


I. Static keywords in process-oriented design

1. Static Global Variables

definition: Before a global variable, the variable is defined as a static global variable, plus the keyword static. Characteristics:
A, the variable allocates memory in the global data area.
B, initialization: If it is not explicitly initialized, it is implicitly initialized to 0 (the automatic variable is random unless explicitly initialized).

C, the visit variable only in the source document is visible, strictly speaking should be the definition of the beginning to the end of this document.

Example (excerpt from C + + Programming Tutorial---Money can editor P103)://file1.cpp//example 1
#include <iostream.h> void fn ();
static int n; Defines a static global variable void main () {
n=20;
cout < <n < <endl;  FN (); }
VOID Fn () {
n++;
cout < <n < <endl; }
D, the Changshime of the const declared under the file scope considers the static storage type.

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. The attentive reader may find that the code in Example 1 will be static int n; To define a static global variable, change to:
int n; Defining a global Variables program works as expected. 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:
A static global variable cannot be used by other files, and (as if it is a different extern) a variable of the same name can be defined in other files, and no conflict will occur;

You can change the example code above to read as follows:

Example 2//file1

#include <iostream.h> void fn ();
static int n; Defines a static global variable (only used in this file) void main () {
n=20;
cout << N <<endl;  FN (); }
File2
#include <iostream.h>
extern int n; (this variable can be referenced in another file) 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 in link. Try to put the static int n; Define a static global variable to change to
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

Definition: Static local variables are defined when a local variable is preceded by a static keyword. Let's first give 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 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. Characteristics:
A, the variable allocates memory in the global data area.
B, initialization: If it is not explicitly initialized, it is implicitly initialized to 0, and subsequent function calls are no longer initialized.
C, it always resides in the global data area until the program finishes running. But its scope is a local scope, and when the function or block of statements that defines it ends, its scope ends.

3. Static function (Note the difference from the static member function of the Class)

Definition: With the static keyword preceded by the return type of the function, the function is defined as a static function. Characteristics:

A. Static functions, unlike normal functions, can only be seen in the file that declares it and cannot be used by other files.

Examples of static functions:

Example 4

#include <iostream.h>
static void Fn ();//Declaration of a function
void Main () {
FN (); }
VOID FN ()//define static function {
int n=10;
cout < <n < <endl; }
The 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.
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 data member};
int myclass::sum=0;//to define and initialize a static data member
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 (a);  M.getsum ();  Myclass N (4,5,6);  N.getsum ();  M.getsum (); }


As you can see, static data members have the following characteristics:

A. 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;

B. Static data members are stored in the global data area. Static data members are defined to allocate space, so they cannot be declared in a class

defined in the. In Example 5, the statement int myclass::sum=0 is defined as a static data member;

C. static data members and ordinary data members comply with PUBLIC,PROTECTED,PRIVATE access rules;

d. Because static data members allocate memory in the global data area, all objects belonging to this class are shared, so it does not belong to

A particular class object whose scope is visible when no class object is generated, that is, when no instance of the class is produced, we can manipulate it;

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:

A. Static data members do not enter the program's global namespace, so there is no conflict with other global names in the program

Possibility

B. Information hiding can be implemented. A static data member can be a private member, while a global variable cannot;

Why must static members be initialized outside of the class?
This is because the static data members of the class that are declared by Static are already born in the global data segment before the main () function begins (see Inside the C + + Object Model page247)! Its life and class objects are asynchronous, (and static semantics indicate that even if there is no class entity, the entity of its static data member is also stored) this time the object's lifetime has not yet started, if you want to initialize the class static data member in the class, let the static data member initialization depends on the entity of the class, How can we satisfy the above static semantics? is the class never instantiated and we never have access to the initialized static data member?

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.
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 data member};
int myclass::sum=0;//to define and initialize a static data member
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; }
void Main () {
Myclass M (a);  M.getsum ();  Myclass N (4,5,6); N.getsum ();
Myclass::getsum ();

}

For static member functions, you can summarize the following points:
A. A function definition that appears outside the class body cannot specify a keyword static;
B. Static members can be accessed from one another, including static member functions accessing static data members and accessing static member letters
Number of
C. Non-static member functions can arbitrarily access static member functions and static data members;  static member functions do not have access to non-static member functions and non-static data members;  because there is no additional overhead for this pointer, static member functions are slightly faster than the class's global functions
of growth;
D. Call a static member function, which can be accessed with the member access operator (.) and (-) is a class object or a pointer to a class object
The PIN calls the static member function;

Static member variables and static member functions in C + + (process-oriented && object-oriented)

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.