Embedded iterators
NestedSmartPointer.cpp
/*** book: "thinkinginc++" * Function: Embedded iterator * Time: September 26, 2014 10:03:03* Author: cutter_point*/#include <iostream> #include < Vector> #include ". /require.h "UsingNamespace std; class obj{static int i, J; Static variable public:void f () {Cout<<i++<<endl;} void G () {cout<<j++<<endl;}}; int obj::i=47;intobj::j=11; classobjcontainer{vector<obj*> A;//This is a container that holds the OBJ class public:void Add (obj* obj) {a.push_back (obj);} Class Smartpointer; Declare a class, for the following write is friend friend Smartpointer; A statement is a friend's premise that the class Smartpointer {objcontainer& oc must be known to be present; unsigned int index; Public:smartpointer (objcontainer& OBJC): OC (OBJC) {index=0;} BOOL operator++ ()//prefix + + {if (index >= oc.a.size ()) Returnfalse; if (oc.a[++index] = = 0) returnfalse; This is to determine whether the + + operation has already executed the//index data value has changed the return true; } bool operator++ (int) {return operator++ (); This postThe results of the prefix + + are the same as the prefixes} obj* operator-> () const//plays, which is the key to this sectionto learning, operator overloading {require (OC). A[index]! = 0, "Zero value returned by smartpointer::operator-> ()"); return Oc.a[index]; Returns the index data of the array}}; Here is a function, just like the one used by the C + + standard library, in order to return to the place where index 0 is smartpointer begin () {returnsmartpointer (*this);}}; int main () {const int sz=10; OBJ O[sz]; Objcontainer OC; for (int i=0; i<sz; ++i) Oc.add (&o[i]); Objcontainer::smartpointer Sp=oc.begin (); do {sp->f (); Sp->g (); }while (++SP); return 0;}
"Thinkinginc++" 60, embedded iterator