Deep analysis of static member function _c language in C + + programming

Source: Internet
Author: User
Tags anonymous

C + + static member functions

Like a data member, a member function can also be defined as static, and the preceding addition of a function in a class becomes a static member function. Such as

  static int volume ();


As with static data members, static member functions are part of a class, not part of an object.

If you want to call a public static member function outside of a class, use the class name and the domain operator "::". Such as

  Box::volume ();


Static member functions are actually also allowed to be invoked through object names, such as

  A.volume ();


But that does not mean that this function belongs to object A, but only to the type of a.

Unlike static data members, the role of static member functions is not to communicate between objects, but to handle static data members.

We know that when a member function (non-static member function) of an object is invoked, the system assigns the starting address of the object to the this pointer of the member function. A static member function does not belong to an object, it has nothing to do with any object, so static member functions do not have this pointer. Since it does not point to an object, you cannot default access to Non-static members in an object (that is, you do not specify an object name when referencing a data member).

It can be said that the fundamental difference between a static member function and a non-static member function is that non-static member functions have this pointer, while static member functions do not have this pointer. This determines that static member functions do not have access to 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 the class and can be referenced directly. In C + + programs, static member functions are used primarily to access static data members without accessing Non-static members.

If you have the following statement in a static member function:

  cout< 
 


However, it is not absolutely impossible to refer to Non-static members in this class, except for default access, because you cannot know which object to look for.

If you must refer to Non-static members of this class, you should add the object name and the member operator ".". Such as

  cout<<a.width<<endl; Referencing non-static members in object A of this class


If a is defined as a box class object and is valid within the current scope, this statement is legitimate.

You can learn more about how to refer to Non-static members by using the following example.

[Example] application of static member functions.

#include <iostream> using namespace std; Class Student//Definition Student class {public:student (int n,int a,float s): num (n), age (a), score (s) {}///define constructor void T
  Otal ();   static float average ();
  Declares a static member function Private:int num;
  int age;
  Float score;      static float sum;      static data member static int count;
static data member};              void Student::total ()//define Non-static member functions {sum+=score;                Cumulative total score count++;           Cumulative number of statistics} float student::average ()//define static member function {return (sum/count);} float student::sum=0;           Initializes an int student::count=0 to a static data member; Initialize int main () {Student stud[3]={//define object array and initialize Student (1001,18,70), Student (1002,19,78) for static data members, S
  Tudent (1005,20,98)};
  int n;
  cout<< "Please input the number of students:";                cin>>n;
  Enter the average score for the number of previous students required for (int i=0;i<n;i++)//Call 3 Total function stud[i].total (); cout<< "The average score of" <<n<< "students is"<<student::average () <<endl;
Call static member function return 0;
 }

The results of the operation are:

Please input the number of Students:3↙ the
average score of 3 students is 82.3333

A few notes on static member function members:
The Stud object array is defined in the main function to make the program concise, defining it with 3 elements and storing 3 students ' data separately. The function of the program is to first ask the user to specify the total score of n students, and then the average score (n by the user input).
Two static data member sum (total score) and count (the cumulative number of students required) are defined in the student class. This is because the values of the two data members need to be cumulative, they are not belong to only one object element, but are shared by each object element, you can see: Their values are constantly changing, and they are the same regardless of the object element, and the memory space is never freed.
Total is a public member function that adds a student's score to sum. A public member function can reference a generic data member (non-static data member) in this object, or a static data member in a class. Score are non-static data members, SUM and count are static data members.
Average is a static member function that can directly refer to a private static data member (without having to add a class name or object name), and the function returns the average of the results.
In the main function, refer to the total function to add the object name (now the object array element name), reference the static member function average function to use the class name or object name.
Consider if you don't define the average function as a static member function. Can the program be compiled? What changes need to be made? Why should I use static member functions? Please analyze its rationale.

C + + static member variables and static member functions
Under normal circumstances, if there are n similar objects, then each object has its own member variables, the different objects of the member variables have values, 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, there are multiple functions in a program file, each function can change the value of a global variable, the value of the global variable is shared by each function. However, the security of the global variable is not guaranteed, because the value of the global variable 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 rarely used in actual development.

If you want to implement data sharing between multiple objects of the same class, and do not use global variables, you can use static member variables.
Static statically member variable

A static member variable is a special member variable that begins with a keyword static. For example:

Class student{
private:
  char *name;
  int age;
  float score;
  static int num; Define NUM as a static member variable public
:
  Student (char *, int, float);
  void say ();

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

A static member variable belongs to a class and does not belong to a specific object, which means that even if multiple objects are created, only one memory is allocated to NUM, and all objects use the data in 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; Class


You can also assign an initial value when initialized:

int student::num = 10; Initialize simultaneous assignment


You can initialize without static, but you must have a data type. Static member variables that are decorated by private, protected, and public can be initialized in this way.

Note: The memory space for a static member variable is not allocated when the class is declared, nor is it allocated when the object is created, but rather when it is initialized.

A static member variable can be accessed either through an object or through a class. Classes are used to access the form:

Class Name:: member variable;


For example:

Access to Student::num by class
= ten;
Access to
Student Stu through objects;
Stu.num = 10;


The two methods are equivalent.

Note: Static member variables are independent of objects, do not occupy the object's memory, but are open to memory outside of all objects, even if they are not created.

Let's look at a complete example:

#include <iostream>
using namespace std;
Class student{
private:
  char *name;
  int age;
  float score;
  static int num; Define NUM as a static member variable public
:
  Student (char *, int, float);
  void say ();
int student::num = 0; Initializes a static member variable
student::student (char *name, int age, float score) {
  this->name = name;
  This->age = age;
  This->score = score;
  num++;
}
void Student::say () {
  //static member variable can be accessed in normal member functions
  cout<<name<< "The Age is" <<age<< ", the result is" < <score<< "(Current total <<num<<" students) "<<endl;
}
int main () {
  //Use Anonymous object
  (New Student ("Xiaoming",)->say ();
  (New Student ("Lilei")->say ();
  (New Student ("Zhang Hua,")->say ();
  (New Student ("Wangkang")->say ();
  return 0;
}

Run Result:

Xiaoming's age is 15, the score is 90 (currently a total of 1 students)
Li Lei's age is 16, the result is 80 (currently a total of 2 students)
Zhang Hua's age is 16, the result is 99 (currently a total of 3 students)
Wangkang's age is 14, the result is 60 (currently a total of 4 students)

In this case, NUM is declared as a static member variable, and the constructor is invoked each time the object is created, adding the value of NUM to 1. Anonymous objects are used because each time an object is created, its say function is used and no other action is performed. Note, however, that using anonymous objects has the risk of memory leaks.

A few notes on 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 variable and ordinary static variable, compile-time in the static data area allocated memory, until the end of the program to release. This means that the static member variable does not allocate memory as the object is created, nor does it free up memory as the object is destroyed. The normal member variable allocates memory when the object is created and frees the 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 student::num = 10;


Initialization can be assigned an initial value, or it can not be assigned. If you do not assign a value, it is initialized by default, typically 0. Variables in the static data area have default initial values, and the variables of the Dynamic Data area (heap area, stack area) are garbage values by default.

4 static member variables can be accessed either by object name or by class name, but are subject to access restrictions for private, protected, and public keywords. When accessed through an object name, the same memory is accessed for different objects.
Static statically member functions

In a class, static, in addition to declaring a static member variable, can also declare statically member functions. Normal member functions can access all member variables, while static member functions can only access static member variables.

We know that when you call a member function of an object (a non-static member function), 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 static member functions do not have this pointer. Since it does not point to an object, it is not possible to access non-static members in that object.

It can be said that the fundamental difference between a static member function and a non-static member function is that non-static member functions have this pointer, while static member functions do not have this pointer. This determines that static member functions do not have access to 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 the class and can be referenced directly. In C + + programs, static member functions are used primarily to access static data members without accessing Non-static members.

If you want to use the static member function of the public attribute in the class, use the class name and the domain Parser "::". Such as:

Student::getnum ();

Static member functions can, of course, be invoked through object names, such as:

Stu.getnum ();

The following is a complete example of getting students ' average grades through static member functions:

 #include <iostream> using namespace std; class student{Private:char;
  int age;
  Float score; static int num; Number of students static float total;
  Total Public:student (char *, int, float);
  void Say (); static float getaverage ();
Static member function, used to get the average score};
int student::num = 0;
float student::total = 0;
  Student::student (char *name, int age, float score) {this->name = name;
  This->age = age;
  This->score = score;
  num++;
Total + = score; The Age of Void Student::say () {cout<<name<< is "<<age<<" and the result is "<<score<<" (current total <<
num<< "Students" <<endl;
  Float Student::getaverage () {return total/num} int main () {(New Student ("Xiaoming,")->say ();
  (New Student ("Lilei")->say ();
  (New Student ("Zhang Hua,")->say ();
  (New Student ("Wangkang")->say ();
  
  cout<< "Average score is" <<student::getaverage () <<endl;
return 0; }

Run Result:

Xiaoming's age is 15, the score is 90 (currently a total of 1 students)
Li Lei's age is 16, the result is 80 (currently a total of 2 students)
Zhang Hua's age is 16, the result is 99 (currently a total of 3 students)
Wangkang's age is 14, the result is 60 (currently a total of 4 students)
average score is 82.25

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

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.