Static Keywords of C ++

Source: Internet
Author: User

Static Keywords of C ++

The static function of C ++ has two usage methods: static in process-oriented programming and static in object-oriented programming. The former applies to common variables and functions, and does not involve classes. The latter mainly describes the role of static in classes.

I. static in process-oriented design

1. Static global variables

Add the keyword static before the global variable, which is defined as a static global variable. Here is an example of a static global variable:

// Example 1

# Include <iostream. h>

Void fn ();

Static int n; // defines the static global variable.

Void main ()

{

N = 20;

Cout <n <endl;

Fn ();

}

 

Void fn ()

{

N ++;

Cout <n <endl;

}

Static global variables have the following features:

  • This variable is stored inGlobal data zone Memory Allocation;
  • Uninitialized static global variables will beAutomatically initialized to 0(The value of the automatic variable is random unless it is explicitly initialized );
  • Static global variablesThe entire file is visible, but not outside the file.;

All static variables are allocated memory in the global data zone, including the static local variables to be mentioned later. For a complete program, the distribution in the memory is as follows:

Code Area

Global data Zone

Heap Area

Stack Zone

In general, dynamic data generated by new is stored in the heap zone, and automatic variables in the function are stored in the stack zone. Automatic variables usually release space as the function exits, and static data (even static local variables in the function) is stored in the global data zone. The data in the global data zone does not release space because the function exits. Careful readers may find that

Static int n; // defines the static global variable.

Change

Int n; // defines the global variable

The program runs normally.

Indeed, defining global variables can share variables in files, but defining static global variables has the following benefits:

  • Static global variables cannot be used by other files;
  • Variables with the same name can be defined in other files without conflict;

You can change the Sample Code as follows:

// Example 2

// File1

# Include <iostream. h>

Void fn ();

Static int n; // defines the static global variable.

Void main ()

{

N = 20;

Cout <n <endl;

Fn ();

}

 

// File2

# Include <iostream. h>

Extern int n;

Void fn ()

{

N ++;

Cout <n <endl;

}

Compile and run Example 2, and you will find that the above Code can be compiled separately, but an error occurs during running. Try

Static int n; // defines the static global variable.

Change

Int n; // defines the global variable

Compile and run the program again to understand the differences between global variables and static global variables (verify the relationship between sharing and protection ).

 

2. Static local variables

Before a local variable, add the keyword static to define the variable as a static local variable.

Here is an example of static local variables:

// Example 3

# Include <iostream. h>

Void fn ();

Void main ()

{

Fn ();

Fn ();

Fn ();

}

 

Void fn ()

{

Static n = 10;

Cout <n <endl;

N ++;

}

Generally, a variable is defined in the function body, and stack memory is allocated to the local variable whenever the program runs the statement. However, as the program exits from the function body, the system will reclaim the stack memory and the local variables will also become invalid.

But sometimes we need to save the variable value between two calls. The general idea is to define a global variable for implementation. In this way, the variable no longer belongs to the function itself, and is no longer only controlled by the function, causing inconvenience to program maintenance.

Static local variables can solve this problem. Static local variables are stored in the global data zone, instead of in the stack. Each value is kept to the next call until the next value is assigned.

Static local variables have the following features:

  • This variable is stored inGlobal data ZoneAllocate memory;
  • Static local variablesThe Declaration is initialized for the first time.That is, subsequent function calls will not be initialized;
  • Static local variables are generally initialized at the Declaration. If no Explicit initialization is performedAutomatically initialized to 0 by program;
  • It always resides inGlobal data zone until program running ends. HoweverScope: local scopeWhen the function or statement block defining it ends, its scope ends;

 

3. Static Functions

Add the static keyword before the return type of the function. The function is defined as a static function. A static function is different from a common function. It can only be seen in the file where it is declared and cannot be used by other files.

Example of static functions:

// Example 4

# Include <iostream. h>

Static void fn (); // declare a static function

Void main ()

{

Fn ();

}

 

Void fn () // defines static functions

{

Int n = 10;

Cout <n <endl;

}

Benefits of defining static functions:

  • Static functions cannot be used by other files;
  • Functions with the same name can be defined in other files without conflict;

 

2. Object-oriented static keywords (static keywords in the class)

1. static data member

Add the keyword static before the declaration of the data member in the class. The data member is the static data member in the class. Here is an example of a static data member.

// 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; // declare a static data member

};

// The following parts cannot appear in the header file

Int Myclass: Sum = 0; // defines and initializes static data members.

 

Myclass: Myclass (int a, int B, int c)

{

This-> 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 (); // Sum = 6

Myclass N (4,5, 6 );

N. GetSum (); // Sum = 21

M. GetSum (); // Sum = 21

}

It can be seen that static data members have the following features:

  • For non-static data members, each class object has its own copy. Static data members are treated as class members. No matter how many objects are defined for this class, static data members also have only one copy in the program, which is shared by all objects of this type. That is to say, static data members are shared by all objects in the class. For multiple objects in this class, static data members only allocate memory once for all objects to share. Therefore, the values of static data members are the same for each object, and their values can be updated;
  • Static data members are stored in the global data zone.Space must be allocated when defining static data members, so they cannot be defined in the class declaration.. In Example 5, the statement int Myclass: Sum = 0 is a member that defines static data;
  • Static data members follow the public, protected, and private access rules like common data members;
  • Because static data Members allocate memory in the global data zone and all objects in this class are shared, they do not belong to a specific class object and are visible in the scope when no class object is generated, that is, when no class instance is generated, we can operate on it;
  • Static data member Initialization is different from general data member initialization. Static data member initialization format: <data type> <class name >:: <static data member name >=< value>
  • Static data members of a class can be accessed in two forms: <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 public Member ), static data members can be referenced in the preceding format in a program;
  • Static data members are mainly used when each object has the same attribute.. For example, for a deposit type, the interest of each instance is the same. Therefore, the interest should be set as the static data member of the deposit class. There are two advantages: first, no matter how many deposit-type objects are defined, interest data members share the memory allocated to the global data area, thus saving storage space. Second, once the interest needs to be changed, the interest of all deposit objects will be changed once;
  • Compared with global variables, static data members have two advantages:
  1. The static data member does not enter the global namespace of the program, so there is no possibility of conflict with other global names in the program;
  2. Information can be hidden. Static data members can be private members, but global variables cannot;

 

2. static member functions

Like static data members, we can also create a static member function that serves all the classes rather than specific objects of a class. Static member functions, like static data members, are internal implementation of the class and are part of the class definition. A common member function generally implies a this pointer, which points to the object itself of the class, because a common member function always belongs to a specific object of a class. Generally, this is the default value. For example, the function fn () is actually this-> fn (). However, compared with common functions, static member functions do not have the this pointer because they are not associated with any objects. In this sense, it cannot access non-static data members of class objects or non-static member functions. It can only call other static member functions. The following 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 (); // declare a static member function

Private:

Int a, B, c;

Static int Sum; // declare a static data member

};

 

// The following must be in the implementation file

Int Myclass: Sum = 0; // defines and initializes static data members.

 

Myclass: Myclass (int a, int B, int c)

{

This-> 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 is 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 ();

}

Static member functions can be summarized as follows:

  • The keyword static cannot be specified for function definitions that appear in external classes;
  • Static members can access each other, including static member functions accessing static data members and accessing static member functions;
  • Non-static member functions can access static member functions and static data members at will;
  • Static member functions cannot access non-static member functions and non-static data members;
  • Without the additional overhead of this pointer, static member functions increase slightly compared with global functions of the class;
  • Call static member functions. You can use the member access operator (.) and (->) for a class object or a pointer to a class object to call a static member function, you can also directly use the following format: <Class Name> :: <static member function name> (<parameter table>) calls the static member function of the class.

 

Differences in static support between VC6 and VC7.1

Class CStaic

{

Public:

CStatic ()

{

}

 

~ CStatic ()

{

}

 

Private:

Static const int defabuffbuffersize = 1024;

};

 

The above code can be compiled in VC ++. net 7.1, but it is not supported on VC6 and may cause a compilation error.

You need to change it to the following statement.

Class CStaic

{

Public:

CStatic ()

{

}

 

~ CStatic ()

{

}

 

Private:

Static const int defabuffbuffersize;

};

 

Const int CStaic: DefaultBufferSize = 1024;

Static Keywords of C ++

The static function of C ++ has two usage methods: static in process-oriented programming and static in object-oriented programming. The former applies to common variables and functions, and does not involve classes. The latter mainly describes the role of static in classes.

I. static in process-oriented design

1. Static global variables

Add the keyword static before the global variable, which is defined as a static global variable. Here is an example of a static global variable:

// Example 1

# Include <iostream. h>

Void fn ();

Static int n; // defines the static global variable.

Void main ()

{

N = 20;

Cout <n <endl;

Fn ();

}

 

Void fn ()

{

N ++;

Cout <n <endl;

}

Static global variables have the following features:

  • This variable is stored inGlobal data zone Memory Allocation;
  • Uninitialized static global variables will beAutomatically initialized to 0(The value of the automatic variable is random unless it is explicitly initialized );
  • Static global variablesThe entire file is visible, but not outside the file.;

All static variables are allocated memory in the global data zone, including the static local variables to be mentioned later. For a complete program, the distribution in the memory is as follows:

Code Area

Global data Zone

Heap Area

Stack Zone

In general, dynamic data generated by new is stored in the heap zone, and automatic variables in the function are stored in the stack zone. Automatic variables usually release space as the function exits, and static data (even static local variables in the function) is stored in the global data zone. The data in the global data zone does not release space because the function exits. Careful readers may find that

Static int n; // defines the static global variable.

Change

Int n; // defines the global variable

The program runs normally.

Indeed, defining global variables can share variables in files, but defining static global variables has the following benefits:

  • Static global variables cannot be used by other files;
  • Variables with the same name can be defined in other files without conflict;

You can change the Sample Code as follows:

// Example 2

// File1

# Include <iostream. h>

Void fn ();

Static int n; // defines the static global variable.

Void main ()

{

N = 20;

Cout <n <endl;

Fn ();

}

 

// File2

# Include <iostream. h>

Extern int n;

Void fn ()

{

N ++;

Cout <n <endl;

}

Compile and run Example 2, and you will find that the above Code can be compiled separately, but an error occurs during running. Try

Static int n; // defines the static global variable.

Change

Int n; // defines the global variable

Compile and run the program again to understand the differences between global variables and static global variables (verify the relationship between sharing and protection ).

 

2. Static local variables

Before a local variable, add the keyword static to define the variable as a static local variable.

Here is an example of static local variables:

// Example 3

# Include <iostream. h>

Void fn ();

Void main ()

{

Fn ();

Fn ();

Fn ();

}

 

Void fn ()

{

Static n = 10;

Cout <n <endl;

N ++;

}

Generally, a variable is defined in the function body, and stack memory is allocated to the local variable whenever the program runs the statement. However, as the program exits from the function body, the system will reclaim the stack memory and the local variables will also become invalid.

But sometimes we need to save the variable value between two calls. The general idea is to define a global variable for implementation. In this way, the variable no longer belongs to the function itself, and is no longer only controlled by the function, causing inconvenience to program maintenance.

Static local variables can solve this problem. Static local variables are stored in the global data zone, instead of in the stack. Each value is kept to the next call until the next value is assigned.

Static local variables have the following features:

  • This variable is stored inGlobal data ZoneAllocate memory;
  • Static local variablesThe Declaration is initialized for the first time.That is, subsequent function calls will not be initialized;
  • Static local variables are generally initialized at the Declaration. If no Explicit initialization is performedAutomatically initialized to 0 by program;
  • It always resides inGlobal data zone until program running ends. HoweverScope: local scopeWhen the function or statement block defining it ends, its scope ends;

 

3. Static Functions

Add the static keyword before the return type of the function. The function is defined as a static function. A static function is different from a common function. It can only be seen in the file where it is declared and cannot be used by other files.

Example of static functions:

// Example 4

# Include <iostream. h>

Static void fn (); // declare a static function

Void main ()

{

Fn ();

}

 

Void fn () // defines static functions

{

Int n = 10;

Cout <n <endl;

}

Benefits of defining static functions:

  • Static functions cannot be used by other files;
  • Functions with the same name can be defined in other files without conflict;

 

2. Object-oriented static keywords (static keywords in the class)

1. static data member

Add the keyword static before the declaration of the data member in the class. The data member is the static data member in the class. Here is an example of a static data member.

// 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; // declare a static data member

};

// The following parts cannot appear in the header file

Int Myclass: Sum = 0; // defines and initializes static data members.

 

Myclass: Myclass (int a, int B, int c)

{

This-> 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 (); // Sum = 6

Myclass N (4,5, 6 );

N. GetSum (); // Sum = 21

M. GetSum (); // Sum = 21

}

It can be seen that static data members have the following features:

  • For non-static data members, each class object has its own copy. Static data members are treated as class members. No matter how many objects are defined for this class, static data members also have only one copy in the program, which is shared by all objects of this type. That is to say, static data members are shared by all objects in the class. For multiple objects in this class, static data members only allocate memory once for all objects to share. Therefore, the values of static data members are the same for each object, and their values can be updated;
  • Static data members are stored in the global data zone.Space must be allocated when defining static data members, so they cannot be defined in the class declaration.. In Example 5, the statement int Myclass: Sum = 0 is a member that defines static data;
  • Static data members follow the public, protected, and private access rules like common data members;
  • Because static data Members allocate memory in the global data zone and all objects in this class are shared, they do not belong to a specific class object and are visible in the scope when no class object is generated, that is, when no class instance is generated, we can operate on it;
  • Static data member Initialization is different from general data member initialization. Static data member initialization format: <data type> <class name >:: <static data member name >=< value>
  • Static data members of a class can be accessed in two forms: <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 public Member ), static data members can be referenced in the preceding format in a program;
  • Static data members are mainly used when each object has the same attribute.. For example, for a deposit type, the interest of each instance is the same. Therefore, the interest should be set as the static data member of the deposit class. There are two advantages: first, no matter how many deposit-type objects are defined, interest data members share the memory allocated to the global data area, thus saving storage space. Second, once the interest needs to be changed, the interest of all deposit objects will be changed once;
  • Compared with global variables, static data members have two advantages:
  1. The static data member does not enter the global namespace of the program, so there is no possibility of conflict with other global names in the program;
  2. Information can be hidden. Static data members can be private members, but global variables cannot;

 

2. static member functions

Like static data members, we can also create a static member function that serves all the classes rather than specific objects of a class. Static member functions, like static data members, are internal implementation of the class and are part of the class definition. A common member function generally implies a this pointer, which points to the object itself of the class, because a common member function always belongs to a specific object of a class. Generally, this is the default value. For example, the function fn () is actually this-> fn (). However, compared with common functions, static member functions do not have the this pointer because they are not associated with any objects. In this sense, it cannot access non-static data members of class objects or non-static member functions. It can only call other static member functions. The following 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 (); // declare a static member function

Private:

Int a, B, c;

Static int Sum; // declare a static data member

};

 

// The following must be in the implementation file

Int Myclass: Sum = 0; // defines and initializes static data members.

 

Myclass: Myclass (int a, int B, int c)

{

This-> 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 is 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 ();

}

Static member functions can be summarized as follows:

  • The keyword static cannot be specified for function definitions that appear in external classes;
  • Static members can access each other, including static member functions accessing static data members and accessing static member functions;
  • Non-static member functions can access static member functions and static data members at will;
  • Static member functions cannot access non-static member functions and non-static data members;
  • Without the additional overhead of this pointer, static member functions increase slightly compared with global functions of the class;
  • Call static member functions. You can use the member access operator (.) and (->) for a class object or a pointer to a class object to call a static member function, you can also directly use the following format: <Class Name> :: <static member function name> (<parameter table>) calls the static member function of the class.

 

Differences in static support between VC6 and VC7.1

Class CStaic

{

Public:

CStatic ()

{

}

 

~ CStatic ()

{

}

 

Private:

Static const int defabuffbuffersize = 1024;

};

 

The above code can be compiled in VC ++. net 7.1, but it is not supported on VC6 and may cause a compilation error.

You need to change it to the following statement.

Class CStaic

{

Public:

CStatic ()

{

}

 

~ CStatic ()

{

}

 

Private:

Static const int defabuffbuffersize;

};

 

Const int CStaic: DefaultBufferSize = 1024;

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.