Summary of the role of C + + static (static members)

Source: Internet
Author: User
Tags class definition

Static is a common keyword in C + + that is used to control how variables are stored and visible.

In a class definition, its members, including data members and member functions, can be declared as static members with the keyword static. The characteristic of a static member is that no matter how many objects the class creates, its static members have only one copy, which is shared by all objects belonging to the class.

From the principle of analysis, we can clearly understand that the data members and member functions of the class are followed by the execution of the class, on the compiler for him to allocate memory space on the stack storage. Static data members and static member functions differ from them in that they are stored in a static storage space when the program starts running.

    • Static data members

In a class, if a data member is declared as static, such a member is called a static data member. Unlike general data members, there is only one copy of a static data member, regardless of how many classes of objects are created.

First, we use an example to analyze static data members.

1#include"stdafx.h"2#include"stdlib.h"3 4 classstudent{5     Static intCount//declare static data members and count the total number of students6     intStudentno;//regular data member, indicating student number7 8  Public:9 Student ()Ten     { Onecount++;//each object created, the number of students plus 1 AStudentno = count;//Assign a value to the current student's study number -     } -  the     voidprint () -     { -printf"student%d", Studentno); -printf"count =%d\n", count); +     } - }; + intStudent::count =0;//initializing a static data member Count A  at int_tmain (intARGC, _tchar*argv[]) - { -Student Student1;//Create a first Student object - student1.print (); -printf"----------------\ n"); -  inStudent Student2;//Create a second student object - student1.print (); to student2.print (); +printf"----------------\ n"); -  theStudent Student3;//Create a third student object * student1.print (); $ student2.print ();Panax Notoginseng student3.print (); -  theSystem"Pause"); +     return 0; A}

The operation results of the above program are as follows:

As you can see from the running result, the count values of all objects are the same, which means they share this data, which means that all objects have only one copy for Count, which is the attribute of the static data member (the action and global variables are similar). Ordinary data members studentno the values of individual objects are different, so it holds the object number of each object.

Description

    A
    1. static data member belongs to a class, not to an object like a normal data member, so we can access a static data member in the form "Class name::". such as: Student::count. A
    2. static data member cannot be initialized in a class because he is not allocated memory space in the class (the storage address in the preceding class is a stack, the static data member store address is a static storage space), so he must be provided with definition and initialization somewhere else. By default, static members are initialized to 0.
    3. static data members, like static variables, are created and initialized at compile time. It already exists before any object of the class is created. As a result, a public static data member can be accessed before the object is defined. After the object is set, the public static data members can also be accessed through objects in the following format:

      Object name, static data member name,

      object name, static data member name,
    4. public,protect,private principle. Therefore, a private static data member cannot be accessed by a class external function or by an object.
    5. The type of a static data member can be the class type to which the member belongs. A non-static data member is qualified as a pointer or reference to an object that declares its own class.
1 class a{2private:3     Static A A1;    // OK 4     A *a1;           // OK 5     A A3;             // Error 6 };

6. Static data members can be used as default arguments, and normal data members are not allowed.

1 classexample{2  Public:3     Static intA;4     intb;5 6     voidFUN1 (inti = a);//correct, A is a static data member7      voidFun2 (inti = b);//error, B is a normal data member8};

7. One of the main reasons that C + + supports static data members is that you can avoid using global variables. Classes that rely on global variables can easily violate the encapsulation principle of object-oriented programs. The primary purpose of a static data member is to define the data that is common to each object of the class, such as statistics, averages, and so on.

    • Static member functions

In a class definition, a static member function is added before the member function. Like static data members, static member functions belong to the entire class and are member functions shared by all objects of the class, rather than functions specific to an object. The format for defining a static member function is as follows:

Static return type function name (argument table)

Like static data members, it follows the principles of public,protect and private. Call the public static member function in the following format:

Class Name:: Static member function (argument table)

Object name. static member function (argument table)

Object name, static member function (argument table)

Let's look at the static member function in an example.

1#include"stdafx.h"2#include"stdlib.h"3 4 classsmall_cat{5 Private:6     intweight;7     Static intTotal_weight;8     Static intTotel_num;9  Public:TenSmall_cat (intW) One     { AWeight =W; -Total_weight + =W; -totel_num++; the     } -  -     voiddisplay () -     { +printf"The small cat weight%d pounds\n", weight); -     } +  A     Static voidTotal_disp () at     { -printf"%d small cat weight", totel_num); -printf"%d pounds\n", total_weight); -     } - }; - intSmall_cat::total_weight =0; in intSmall_cat::totel_num =0; -  to int_tmain (intARGC, _tchar*argv[]) + { -Small_cat W1 (1), W2 (3), W3 (2); the W1.display (); * W2.display (); $ W3.display ();Panax Notoginseng  - Small_cat::total_disp (); the  +System"Pause"); A     return 0; the}

Program Run Result:

Description

  1. Static member functions can be defined inline or inside and out, defined outside the class, without the need to add static in front of it.
  2. In general, static member functions are primarily used to access global variables or static data members in the same class.
  3. Private static member functions cannot be accessed by external functions and objects of the class.
  4. One reason to use a static member function is that it can be used to process static data members before any objects are created, which is not possible with ordinary member functions.
  5. The compilation system qualifies the static member function as an internal connection, that is, a function with the same name in the file connected to the current file does not conflict with the function and maintains the security of the function, which is another reason for using static member functions.
  6. this pointer in a normal member function, which points to the object itself, without the this pointer in a static member function because it is not associated with a particular object. Call a static member function using the following format: :: static member function name ();
  7. Static member functions cannot be declared const because static members are not part of any object, after all, declaring a member function as Const is a promise not to modify the object to which the function belongs.
  8. A static member function cannot be declared as a virtual function.
  9. In general, a static member function cannot access a non-static member of a class. If you do, a static member function can access the non-static members of the object only through the object name (or a pointer to the object name). Such as:
1 Static void display (Small_cat &W)2{3     printf ("The Small cat weight%d pounds\n", w.weight); 4 }
    • Extended

Static local Variables

Static local variables belong to static storage, which has the following characteristics:

(1) A static local variable is defined within a function, but unlike an automatic variable, it is present when called and disappears when the function exits. A static local variable always exists, that is, its lifetime is the entire source program.

(2) The lifetime of a static local variable is the entire source program, but its scope is still the same as the automatic variable, that is, the variable can only be used within the function that defines it. After exiting the function, it cannot be used even though the variable continues to exist.

(3) allows the initial value to be assigned to the static local quantity of the construction class. If the initial value is not assigned, it is automatically assigned by the system. The numeric variable automatically assigns the initial value 0, and the character variable assigns a null character.

(4) If the static local variable of the basic type is not assigned the initial value in the description, the system automatically assigns 0 values. The value of the automatic variable is indeterminate if it is not assigned the initial values. According to the characteristics of static local variables, it can be seen that it is a lifetime of the entire source file amount. Although it cannot be used after the function that defines it, it can continue to be used if the function that defines it is called again, and the value left after the previous call is saved. Therefore, you can consider static local variables when you call a function multiple times and require the values of certain variables to be preserved between calls. Although this can be achieved with global variables, global variables sometimes cause unintended side effects, so it is advisable to use local static variables.

Summary of the role of C + + static (static members)

Related Article

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.