Today, when I read "C ++ strategies and tactics", I found a very interesting piece of code:
1 class Complex_rep { 2 private: 3 friend class Complex; 4 double real_d; 5 double image_d; 6 Complex_rep(double r, double i) : real_d(r), image_d(i) { 7 8 } 9 };10 11 class Complex {12 private:13 Complex_rep *rep;14 public:15 Complex(double r, double i)16 :rep(new Complex_rep(r, i)) {}17 ~Complex() { delete rep; }18 };
You can see that complex represents the data structure of the complex, but it is interesting that the data members (real and virtual parts of the complex) are not stored in the complex, but in a complex_rep class. In complex_rep, complex is declared as a friend Meta class, so that complex can access all the Members and methods in complex_rep. At the same time, the constructor of complex_rep is declared as private, so that instances of complex_rep cannot be created outside the class body and can only be created through complex of the youyuan class.
This means that complex_rep is unique to the complex class and can only be created and accessed through complex. No other class can create a complex_rep instance.
(This method is called handle in C ++ only when I look at Chapter 3 )).
The technique of declaring constructors as private is also applied in the "Singleton mode" of the design mode. A singleton class is defined as follows:
1 class Singleton { 2 public: 3 static Singleton* instance(); 4 protected: 5 Singleton(); 6 private: 7 static Singleton* _instance; 8 }; 9 10 Singleton* Singleton::_instance = 0;11 12 Singleton* Singleton::instance() {13 if(_instance == 0) {14 _instance = new Singleton;15 }16 return _instance;17 }
The customer only accesses this single piece through the instance () member function. The Variable _ instance is initialized to 0, while the static member function interface () returns its variable value. If its value is 0, it is initialized with a unique instance. Instance () is initialized using lazy: _ instance is not created and saved until it is accessed for the first time.