Taking a smart pointer class as an example, a smart pointer refers to an object.
In fact, the development of STL iterators requires to reload these two operators. in the previous article, we analyzed that the STL iterator must not only use the template technique, but also the reload technique.
1 # include <iostream> 2 using namespace STD; 3 Class Screen 4 {5 6 public: 7 friend ostream & operator <(ostream & OS, screen & S ); 8 int action () {return + data;} 9 screen (INT I = 0): Data (I) {} 10 private: 11 int data; 12 }; 13 ostream & operator <(ostream & OS, screen & S) 14 {15 OS <S. data; 16 return OS; 17} 18 class u_ptr19 {20 friend class screenptr; 21 screen * P; 22 size_t use; 23 u_ptr (screen * PP): p (PP ), Use (1) {}24 ~ U_ptr () {Delete P ;}25}; 26 class screenptr27 {28 private: 29 u_ptr * PTR; 30 public: 31 screenptr (screen * P ): PTR (New u_ptr (p) {} 32 screenptr (screenptr & orgi_p): PTR (orgi_p.ptr) {++ PTR-> use;} 33 ~ Screenptr () {If (-- PTR-> Use = 0) delete PTR;} 34 screen & operator * () 35 {36 return * (PTR-> P ); 37} 38 screen * operator-> () 39 {40 return PTR-> P; 41} 42}; 43 class gao44 {45 private: 46 screenptr * P; 47 public: 48 Gao (screenptr * q): p (q) {} 49 screenptr & operator-> () 50 {51 return * P; 52} 53}; 54 int main () 55 {56 57 screenptr (new screen (5); 58 cout <"* operator" <* PTR <Endl; 59 cout <"-> operator" <PTR-> acti On () <Endl; 60 screenptr * PP = & PTR; 61 Gao D (PP); 62 cout <"! "<D-> action () <Endl; 63 system (" pause "); 64}
The Code logic here is as follows: 1. first, define a simple encapsulation u_ptr, which is actually a pointer to screen + A reference count encapsulation 2. then define the true smart pointer class screenptr, whose member is u_ptr,
3. then define the constructor and the copy constructor (reference count ++)
4. define the destructor. The destructor of the u_ptr class is called only when -- use = 0. finally, in order to make the class screenptr behave like a pointer, reload operator * and->
* Is A unary operator. As a member function, it is invisible. The returned reference pointing to screen> is a unary operator. Although it looks like a binary operator, it is also invisible.
Note that the returned value is a screen pointer?As you can understand, for a pointer type variable p, p-> action (), it indicates that its member // action () is returned as a member function of the screen class.
For the screenptr class that we want to overload, we call-> the screenptr object. Therefore, a pointer to screen is returned, and then the compiler automatically binds its members, that is to say, the screenptr object SP-> action () means (sp. operator-> ()-> action ())
More generally, in addition to returning a pointer, you can also return a reference to a class object that has already been overloaded with the-> operator, then the compiler recursively calls the reloaded-> until there is a return pointer, such as the class Gao above.