As with static data members, static member functions are shared by all objects, not individually, because static member functions do not pass the this pointer, so static member function can only access static members and cannot access non-static members. But non-static can access static members.
1#include <iostream>2 using namespacestd;3 classx{4 inti;5 Static intJ;6 Public:7XintIi=0): I (ii) {8j = i;//non-static member function can access static member function or data9 }Ten intVal ()Const{returni;} One Static intincr () { A //i++; Error:static member function can not access non-static member data - return++J; - } the Static intf () { - //!val () error:static member function can not access non-static member function - returnincr (); - } + - }; + intX::j =0; A intMain () { at x x; -x* XP = &x; - x.f (); -Xp->f (); - x::f (); -System"Pause"); in return 0; - to}
When an object accesses a static member, it can pass the dot operator and the arrow operator. This connects the static member function to an object, or it can be accessed directly using the Classname::static member Fucntion name.
Sometimes you can set the constructor to private, as in the following example
1 classegg{2 StaticEgg E;3 inti;4Egg (intII): I (ii) {}5Egg (Constegg&);//Prevent copy-construction6 Public:7 Staticegg* instance () {return&e;}8 intVal ()Const{returni;}9 };Ten OneEgg Egg::e ( -); A intMain () { - //! Egg x (0); Error can ' t create an Egg -cout << egg::instance ()->val () <<Endl; theSystem"Pause"); - return 0; - -}
To not allow the class to copy the created object, a private copy constructor is added
Egg (const egg&);//prevent copy-construction
Such a class would not create objects like the following
Egg e=*egg::instance ();
Static member function