C + + static member variables and static member functions

Source: Internet
Author: User
Tags function 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 keyword 1 in process-oriented design, global variable

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; Defining static global Variables
void Main ()
{
n=20;
cout < <n < <endl;
FN ();
}

VOID Fn ()
{
n++;
cout < <n < <endl;
} D, the const Changshime 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. Careful readers may find that the code in Example 1 will

static int n; Defining static global Variables

Switch

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:

Static global variables cannot be used by other files; (as if it were a different extern)
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:

Example 2
File1
#include <iostream.h>
VOID Fn ();
static int n; //define static global variables (only available 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; 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. 2. Static local variable definition: Static local variables are defined when the 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 functions (note the difference from static member functions of a Class) definition: The function is defined as a static function by adding the static keyword to its return type.    Features: A, static function and ordinary function, it can only be declared in the file is visible, can not 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 functions
{
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 at rest
};
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 ();

You can see 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 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->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 ();
Private
int a,b,c;
static int sum;//declares a data member at rest
};
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 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.
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 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 a pointer to a class object.

C + + static member variables and static member functions

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.