Sometimes, write c ++ CodeAn instance is initialized, that is, an object is created using the class definition.
For some reason, you need to use this instance in some other places. Of course, you cannot redefine an object. At this time, we can only find a way to obtain the pointer of the previous object. What should I do when pointers cannot be passed parameters? You can use static data members to define an object using the following method.
Class testinstance {public: testinstance (void );~ Testinstance (void );
Public: static testinstance * instance () {If (_ instance = NULL) {_ instance = new testinstance ();} return _ instance;} static void release () {If (_ instance! = NULL) {Delete _ instance; _ instance = NULL;} PRIVATE: static testinstance * _ instance;} testinstance * testinstance: _ instance = NULL;
We use static testinstance * _ instance as the static data member to point to the object itself. This design requires class initialization using the following methods:
Testinstance _ testinstance = testinstance: instance ();
In this way, we can store the pointer of the _ testinstance instance to its own data member.
When we need a testinstance instance, we only need to use the following statement to obtain its pointer:
Testinstance * testinstance = testinstance: instance ();
Of course, remember to manually release objects when they are not needed:
Testinstance: release ();
This technique is useful in many cases!