1. static member functions
(1) A static member function is a special member function in a class that belongs to the entire class.
(2) public static member functions can be accessed directly through the class name
(3) public static member functions can be accessed by object name
(4) Definition of a static member function: modifying member functions directly through the static keyword
Example of a "programming experiment" static member function
#include <stdio.h>classtest{Private: inti; Static intS_j; Public: intGeti (); Static voidStaticfunc (Const Char*s); Static voidStaticseti (Test&d,intv); Static intstaticgetj ();};intTest::geti () {returni;}voidTest::staticfunc (Const Char*s) {printf ("Staticfunc:%s\n", s);}voidTest::staticseti (Test&d,intv) {D.I=v; //i = V;//static member functions cannot access non-static member variablesS_j = v;//legal, accessing static member variables}intTest::staticgetj () {returnS_j;}intTest::s_j =0;intMain () {Test::staticfunc ("main Begin ...");//calling a static member function from a class nameTest t; Test::staticseti (T,Ten); printf ("t.i =%d\n", T.geti ()); printf ("S_j =%d\n", T.STATICGETJ ());//calling static member functions by object nameTest::staticfunc ("main End ...");//calling a static member function from a class name return 0;}
2. static member functions VS ordinary member functions
|
Static member functions |
Ordinary member functions |
All objects Shared |
Yes |
Yes |
Implied this pointer |
No |
Yes |
Accessing ordinary member variables/functions |
No |
Yes |
accessing static member variables/functions |
Yes |
Yes |
Called directly through the class name |
Yes |
No |
The object can be directly called by the |
Yes |
Yes |
"Programming Labs" solution
#include <stdio.h>classtest{Private: Static intCcount; Public: Test () {ccount++;} ~test () {--Ccount;} Static intGetCount () {returnccount;}};intTest::ccount =0;intMain () {printf ("count =%d\n", Test::getcount ());//0, calling the function through the class nameTest T1; Test T2; printf ("count =%d\n", T1.getcount ());//2, calling functions by object nameprintf"count =%d\n", T2.getcount ());//2, calling functions by object nameTest* pt =NewTest (); printf ("count =%d\n", Pt->getcount ());//3 Deletept; printf ("count =%d\n", Test::getcount ());//2, calling the function through the class name return 0;}
3. Summary
(1) A static member function is a special member function in a class
(2) The static member function has no hidden this parameter
(3) Static member functions can be accessed directly through the class name
(4) Static member functions can only access static member variables/functions directly
The static member function of class 26th