C + + learning static member variables and static member functions

Source: Internet
Author: User

In general, if there are N homogeneous objects, each object has its own member variable, and the member variables of the different objects have their own values, which are irrelevant to each other. But sometimes we want to have one or several member variables that are common to all objects, which enables data sharing.

You can use global variables to achieve the purpose of sharing data. For example, in a program file has multiple functions, each function can change the value of global variables, the value of the global variable for each function sharing. However, the security of global variables is not guaranteed, because the value of global variables can be freely modified everywhere, it is possible to accidentally mistake, the value of the global variable is modified, resulting in the failure of the program. Therefore, global variables are seldom used in real-world development.

You can use static member variables if you want to implement data sharing between multiple objects of the same type, and do not use global variables.

Static statically member variable
 class   student{ private  :  char  *name;     int   age;     float   score;   static  int  num; //  defines num as a static member variable  public   char  *, int , float  );  void   Say ();};  

This code declares a static member variable num, which is used to count the number of students.

Static member variables belong to a class and do not belong to a specific object, which means that even if multiple objects are created, only one copy of the memory is allocated to NUM, and all objects use the data in this memory. When an object modifies num, it also affects other objects.

The static member variable must be initialized before it can be used, otherwise the link is wrong. For example:

int Student::num;  // Initialize

You can also assign an initial value at initialization time:

int ten;  // simultaneous assignment of initialization

Initialization can be non-static, but must have a data type. Static member variables that are modified by private, protected, public, can be initialized in this way.

Note: The memory space of a static member variable is not allocated when declaring the class, nor is it allocated when the object is created, but rather at initialization time.

Static member variables can be accessed either through an object or through a class. The form accessed through the class is:

Class Name:: member variable;

For example:

// access by Class Ten ; // Access by Object  Ten;

Both of these methods are equivalent.

Note: The static member variable is independent of the object, does not occupy the object's memory, but opens up memory outside of all objects, even if the object is not created.

#include <iostream>using namespacestd;classstudent{Private:    Char*name; intAge ; floatscore; Static intNum//To define NUM as a static member variable Public: Student (Char*,int,float); voidsay ();};intStudent::num =0;//initializing static member variablesStudent::student (Char*name,intAgefloatscore) {     This->name =name;  This->age =Age ;  This->score =score; Num++;}voidStudent::say () {//static member variables can be accessed in normal member functionscout<<name<<"The Age is"<<age<<", the results are"<<score<<"(Current total"<<num<<"students)"<<Endl;}intMain () {//using anonymous objects(NewStudent ("Xiao Ming", the, -)),say (); (NewStudent ("Li Lei", -, the)),say (); (NewStudent ("Zhang Hua", -, About)),say (); (NewStudent ("Wangkang", -, -)),say (); return 0;}

In this example, NUM is declared as a static member variable, and each time the object is created, the constructor is called and the value of num is added 1. Anonymous objects are used because only its say function is used every time the object is created, and no further action is made. Note, however, that using anonymous objects has the risk of memory leaks.

A few notes about static data members:

1) A class can have one or more static member variables, all of which share these static member variables and can reference it.

2) static member variables, like normal static variables, allocate memory in the static data area at compile time and are released at the end of the program. This means that static member variables do not allocate memory with the creation of the object, and do not release memory with the object's destruction. The normal member variable allocates memory when the object is created and frees memory when the object is destroyed.

3) Static member variables must be initialized and can only be performed outside the class body. For example:

int ten;

Initial values can be assigned or not assigned when initializing. If you do not assign a value, it will be initialized by default, typically 0. Variables in the static data area have default initial values, while variables in the Dynamic Data area (heap, stack) are garbage values by default.

4) Static member variables can be accessed either through the object name or through the class name, but subject to the access restrictions of the private, protected, and public keywords. When accessed through the object name, the same amount of memory is accessed for different objects.

Static Statics member function

Static member functions can also be declared in a class, in addition to declaring static member variables. Ordinary member functions can access all member variables, whereas static member functions can only access static member variables.

We know that when invoking a member function (non-static member function) of an object, the system assigns the starting address of the current object to the this pointer. A static member function does not belong to an object, it has nothing to do with any object, so the static member function does not have the this pointer. Since it does not point to an object, you cannot access non-static members of that object.

It can be said that the fundamental difference between a static member function and a non-static member function is that a non-static member function has this pointer, whereas a static member function does not have the this pointer. This determines that a static member function cannot access non-static members in this class.

Static member functions can refer directly to static data members in this class, because static members are also part of a class and can be referenced directly. In C + + programs, static member functions are primarily used to access static data members without accessing non-static members.

If you want the static member function of the public property to be out of class, use the class name and the domain resolver "::". Such as:

Student::getnum ();

Of course, you can also call static member functions through the object name, such as:

Stu.getnum ();

The following is a complete example of the student's average score through a static member function:

#include <iostream>using namespacestd;classstudent{Private:    Char*name; intAge ; floatscore; Static intNum//Number of students    Static floatTotal//Total Public: Student (Char*,int,float); voidsay (); Static floatGetaverage ();//static member function to get the average score};intStudent::num =0;floatStudent::total =0; Student::student (Char*name,intAgefloatscore) {     This->name =name;  This->age =Age ;  This->score =score; Num++; Total+=score;}voidStudent::say () {cout<<name<<"The Age is"<<age<<", the results are"<<score<<"(Current total"<<num<<"students)"<<Endl;}floatStudent::getaverage () {returnTotal/num;}intMain () {(NewStudent ("Xiao Ming", the, -)),say (); (NewStudent ("Li Lei", -, the)),say (); (NewStudent ("Zhang Hua", -, About)),say (); (NewStudent ("Wangkang", -, -)),say (); cout<<"average score is"<<student::getaverage () <<Endl; return 0;}

In the preceding code, the NUM, total is declared as a static member variable, and Getaverage is declared as a static member function. In the Getaverage function, only the total, num two static member variables are used.

C + + learning static member variables and static member functions

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.