/*
Classes that contain static data members do not allocate storage space for static data members when they are created, you can treat static data members as a global variable and encapsulate them in a class for two purposes
(1) Restricting the scope of the variable, for example, by placing it in the private part of the class declaration, it can only have direct access to function members of that class object
(2) It can increase the readability and maintainability of a program by physically putting the relevant global variables and related operations together.
And
Static member functions
1) A static member function is a shared resource of all objects of its kind, with only a common copy, so it cannot directly access the non-crystalline data members, which must be accessed through an object of that class.
General member functions can access non-static data members directly
2) access to static member functions is basically a static data member or a global variable
3) class Name:: Static member function name
4) A stumbled IDE static member function differs from a non-static member function, it does not need to create any object of that class to be called, while the use of static member functions is not specific to a particular object, but when used, the system
It is best to have objects of this class already exist, otherwise meaningless
5) A static member function cannot make a virtual function, except that the static member function and the table member function have the same name as the parameter type would be illegal
*/
#include <iostream>
using namespace Std;
Class Student {
Public
void Set (String str) {
NAME=STR;
number++;
}
static int Printnumber () {///statics member function
cout<<number<< "Total Numbers" <<endl;
}
void Print () {
cout<<name<< "->students is" <<number<< "numbers" <<endl;
}
Private
static int number;//quiescent data
String name;
};
int student::number=0;//static Data initialization
int main () {
Student s,s1;
Student::P rintnumber ();//Call static member function
S.set ("Smith");
S.print ();
Student::P rintnumber ();
S1. Set ("Jenny");
S1. Print ();
S1. Printnumber ();
return 0;
}
Results:
0total numbers
Smith->students are1numbers
1total numbers
Jenny->students are2numbers
2total numbers
--------------------------------
Process exited after 0.2102 seconds with return VA
Please press any key to continue ...
Static member data and static member functions