C ++ collection-constructor (2)
C ++ collection-constructor (2)
Preface
In Constructor (1), we discuss some applications of default constructor. Here we will discuss some other famous constructors and their application scenarios.
Instance
# Include
Using namespace std; class Complex {protected: int real = 0; int imag = 0; public: // The default Complex () {cout <Complex () <endl ;} complex (int r, int I): real (r), imag (I) {cout <Complex (int r, int I) <endl ;} // specify other constructors to complete their work, which is equivalent to entrusting Complex (int r): Complex (r, 0) {cout <Complex (int r) <endl ;} complex (Complex & com) // The copy construction parameter must be of the reference type {cout <Complex (Complex & com) <endl; real = com. real; imag = com. imag;} Complex & operator = (Complex & com) // The parameters here can be non-referenced {cout <Complex & operator = (Complex & com) <endl; real = com. real; imag = com. imag; return * this ;}}; int main () {Complex com1; // default initialization, call Complex () to construct cout by default <--- <endl; complex com2 (com1); // directly initialize, call Complex (Complex & com) cout <--- <endl; Complex com3 = com1; // value assignment initialization, call Complex (Complex & com) cout <--- <endl; Complex com4; // default initialization, call Complex () to construct cout by default <--- <endl; com4 = com1; // value assignment, call operator = (Complex & com) cout <--- <endl; Complex com5 (1, 1 ); // call the specified constructor Complex (int r, int I) cout <--- <endl; Complex com6 (1); cin. get (); return 0 ;}
Run
Famous constructor 1. copy constructor
Similar to Complex (Complex & com); the parameter must be of the reference type, which is the copy constructor.
The so-called shallow copy and deep copy are for pointer members, and there is no difference between common members. For pointer members, if only one copy of the address is copied, It is a shortest copy. if the content is copied, It is a deep copy.
If only one address is copied, multiple objects share the same resource. When one of the objects is destroyed, the resources are destroyed. Other objects are affected. This is the so-called shallow copy and deep copy problems.
2. Delegate Construction
In the new standard, the constructor similar to Complex (int r): Complex (r, 0) {} is called a Delegate constructor.
Similar to the design model: delegated, can be well understood. Complex (int r) handed over the actual work to Complex (r, 0 ).