Home>

C++ static member functions

Similar to data members,Member functions can also be defined as static,Declaring a function in a class followed by static becomes a static member function.Such as

 static int volume ();

Like static data members,Static member functions are part of the class,Not part of the object.

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

 box ::volume ();

Actually it is also allowed to call static member functions by object name,Such as

 a.volume ();

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

Unlike static data members,The purpose of static member functions is not to communicate between objects,It is to be able to handle static data members.

we know,When a member function (non-static member function) of an object is called, the system will assign the starting address of the object to the this pointer of the member function. And static member functions do not belong to an object,It has nothing to do with any object,So static member functions do not have this pointers. Since it doesn't point to an object,It is not possible to provide default access to non-static members in an object (that is, without specifying an object name when referring to a data member).

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 a this pointer, while a static member function does not have a this pointer. This determines that static member functions cannot access non-static members in this class.

Static member functions can directly reference static data members in this class.Because static members also belong to classes,Can be directly quoted.In C++ programs, static member functions are mainly used to access static data members.Without accessing non-static members.

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

 cout<height<endl;//If height has been declared as static, refer to a static member in this class,legitimate
  cout<width<endl;//If width is a non-static data member,illegal

However, it is not absolutely impossible to refer to non-static members in this class,Just can't make default access,Because it is impossible to know which object to look for.

If you must reference non-static members of this class,The object name and member operator "." Should be added. Such as

 cout<a.width<endl;//Refer to non-static members in object a of this class

Assuming that a has been defined as a box object and is valid in the current scope,This statement is legal.

The following example can learn more about the specific method of referencing non-static members.

[Example] Application of static member function.

#include<iostream>
using namespace std;
class student //Define the student class
{
public:
  student (int n, int a, float s):num (n), age (a), score (s) {} //define the constructor
  void total ();
  static float average ();//Declaring 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 a non-static member function
{
  sum +=score;//accumulate total score
  count ++;//Total number of people counted
}
float student ::average () //Define a static member function
{
  return (sum/count);
}
float student ::sum=0;//Initialize static data members
int student ::count=0;//Initialize static data members
int main ()
{
  student stud [3]={//define object array and initialize
   student (1001,18,70),   student (1002,19,78),   student (1005,20,98)
  };
  int n;
  cout<""please input the number of students:";
  cin>>n;//Enter the average grade of how many students are required before
  for (int i=0;i<n;i ++) //call the total function 3 times
   stud [i] .total ();
  cout<""the average score of"<<n<<>
  //Call a static member function
  return 0;
}

The result is:

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

A few notes about members of static member functions:

An array of stud objects is defined in the main function,To keep the program simple,It is only defined that it contains 3 elements and stores the data of 3 students respectively.The role of the program is to first find the total score of the n students specified by the user,Then calculate the average score (n is entered by the user).

Two static data members sum (total score) and count (cumulative number of students to be counted) are defined in the student class. This is because the values ​​of these two data members need to be accumulated.They do n’t belong to only one object element,But shared by each object element,It can be seen:their values ​​are constantly changing,And no matter for which object element,All the same,And never free up memory space.

total is a public member function,Its role is to add a student's grade to the sum. Public member functions can reference general data members (non-static data members) in this object, or they can reference static data members in the class.score is a non-static data member,sum and count are static data members.

average is a static member function,It can directly reference private static data members (without the need to add class or object names), and the function returns the average of the results.

In the main function, you need to add the object name (to use the object array element name) to refer to the total function, and use the class name or object name to refer to the static member function average function.

Think about it, wouldn't it be fine to define the average function as a static member function?Does the program compile?What changes need to be made?Why use static member functions?Please analyze the reasons.

Static member variables and static member functions

In general,If there are n similar objects,Then each object has its own member variable,Member variables of different objects have values,Irrelevant.But sometimes we want to have one or more member variables common to all objects,This 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 values ​​of global variables are shared among functions.But the safety of using global variables is not guaranteed,Since the value of global variables is free to modify everywhere,Very likely to make a mistake by accident,The value of the global variable is modified,Causes the program to fail.Therefore, global variables are rarely used in actual development.

If i want to share data between multiple objects of the same type,Also don't use global variables,Then you can use static member variables.

static member variables

A static member variable is a special member variable.It starts with the keyword static. E.g:

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.

static member variables belong to the class,Does not belong to a specific object,This means,Even if you create multiple objects,Also allocates only one copy of memory for num,All objects use the data in this memory.When an object changes num, it also affects other objects.

Static member variables must be initialized before they can be used.Otherwise the link is wrong.E.g:

int student ::num;//Init

You can also assign initial values ​​during initialization:

int student ::num=10;//initialization and assignment

It can be initialized without static, but it must have a data type.Private member protected private variables can be initialized in this way.

Note:The memory space of static member variables is neither allocated when the class is declared,Nor is it allocated when the object is created,Instead, it is allocated during initialization.

static member variables can be accessed both through objects,It can also be accessed through classes.The form to access through the class is:

Class name ::member variable;

E.g:

//Access by class
student ::num=10;
//Access through objects
student stu;
stu.num=10;

These two approaches are equivalent.

Note:The static member variable has nothing to do with the object,Does not occupy the memory of the object,But open up memory outside all objects,Accessible even without creating objects.

Take a 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;//Initialize static member variables
student ::student (char * name, int age, float score) {
  this->name=name;
  this->age=age;
  this->score=score;
  num ++;
}
void student ::say () {
  //You can access static member variables in ordinary member functions
  cout<name<"'s age is"<age<" ;, and the grade is"<score<") "<endl;
}
int main () {
  //Use anonymous objects
  (new student ("Xiao Ming", 15, 90))->say ();
  (new student ("Li Lei", 16, 80))->say ();
  (new student ("Zhang Hua", 16, 99))->say ();
  (new student ("Wang Kang", 14, 60))->say ();
  return 0;
}

operation result:

Xiao Ming's age is 15 and his grade is 90 (1 student currently)
Li Lei's age is 16 with a grade of 80 (currently 2 students)
Zhang Hua's age is 16 and her grade is 99 (currently 3 students)
Wang Kang's age is 14 and his grade is 60 (currently 4 students)

In this example, num is declared as a static member variable.Every time an object is created,Will call the constructor,Increment the value of num by 1. The reason for using anonymous objects,This is because every time an object is created, its say function is used and no other operations are performed.Please note, however,There is a risk of memory leaks when using anonymous objects.

A few notes about static data members:

1) A class can have one or more static member variables,All objects share these static member variables,Can quote it.

2) static member variables are the same as ordinary static variables,Allocate memory in the static data area when compiling,It is not released until the end of the program.This means,static member variables do not allocate memory with the creation of the object,It also does not release memory with the destruction of the object.And ordinary member variables allocate memory when the object is created,Free up memory when the object is destroyed.

3) Static member variables must be initialized,And only in vitro.E.g:

int student ::num=10;

Initial values ​​can be assigned during initialization,It can also be left unassigned.If not assigned,Then it will be initialized by default,Usually 0. Variables in the static data area have default initial values.The variables in the dynamic data area (heap area, stack area) are garbage values ​​by default.

4) Static member variables can be accessed through object names,Also accessible by class name,However, there are restrictions on access to the private, protected, and public keywords.When accessed by object name,For different objects,The same memory is accessed.

static member function

In a class, in addition to declaring static member variables,You can also declare static member functions.Ordinary member functions have access to all member variables,A static member function can only access static member variables.

we know,When a member function (non-static member function) of an object is called, the system will assign the starting address of the current object to the this pointer. And static member functions do not belong to an object,It has nothing to do with any object,So static member functions do not have this pointers. Since it doesn't point to an object,You cannot access non-static members of this 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 a this pointer, while a static member function does not have a this pointer. This determines that static member functions cannot access non-static members in this class.

Static member functions can directly reference static data members in this class.Because static members also belong to classes,Can be directly quoted.In C++ programs, static member functions are mainly used to access static data members.Without accessing non-static members.

If i want to call a static member function of the public property outside the class,Use the class name and domain resolver "::". Such as:

student ::getnum ();

Of course, you can also call static member functions by object name.Such as:

stu.getnum ();

Here is a complete example,Obtain the student's average grade through a static member function:

#include<iostream>
using namespace std;
class student {
private:
  char * name;
  int age;
  float score;
  static int num;//Number of students
  static float total;//Total score
public:
  student (char *, int, float);
  void say ();
  static float getaverage ();//static member function,Used to get average grades
};
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;
}
void student ::say () {
  cout<name<"'s age is"<age<"and grade is"<score<") "<endl;
}
float student ::getaverage () {
  return total/num;
}
int main () {
  (new student ("Xiao Ming", 15, 90))->say ();
  (new student ("Li Lei", 16, 80))->say ();
  (new student ("Zhang Hua", 16, 99))->say ();
  (new student ("Wang Kang", 14, 60))->say ();
  cout<"average score"
  return 0;
}

operation result:

Xiao Ming's age is 15 and his grade is 90 (1 student currently)
Li Lei's age is 16 with a grade of 80 (currently 2 students)
Zhang Hua's age is 16 and her grade is 99 (currently 3 students)
Wang Kang's age is 14 and his grade is 60 (currently 4 students)
Average score 82.25

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

c
  • Previous Detailed ASPNET forms authentication
  • Next Briefly introduce friend functions and friend classes in C ++ programming