Initializes the object to copy
Initializes the object will call the constructor, the different initialization method will call a different constructor:
- If the object is initialized with the argument passed in, then calls the general constructor, we might as well call this common initialization;
- If (an existing object) data to initialize the object with other objects, it will call the copy constructor, a copy of which is initializes.
For simple class, the default copy constructor is generally enough to use, we do not need to explicitly define the function similar to a copy constructor. However, when the class while holding other resources, such as memory dynamically allocated, pointers to other data, a pointer and the like, the default copy constructor will not be able to copy these resources, and must explicitly define copy constructor, a complete copy of the object All data.
Such objects held by other resources together with a copy, is called a deep copy, we must explicitly define a copy constructor to achieve the purpose of deep copy.
= Operator overloading
:: & the Array the Array operator = ( const the Array & ARR) { // overloaded assignment operator IF ( the this {= & ARR!) // if judged to their assigned the this -> m_len = arr.m_len; Free ( the this -> M_P ); // release the original memory the this -> M_P = ( int *) calloc ( the this -> m_len, the sizeof ( int )); the memcpy ( the this -> M_P, arr.m_p, m_len * the sizeof ( int )); } return * the this; }
About why should return * this:
Explained as follows:
For simplicity of programming, sometimes you need to assign a series, such as: x = y = z = 15; since the use of the right binding assignment, so the above statement is interpreted as: x = (y = (z = 15));
In order to achieve series assignment, the assignment operator must return a reference to the operator of the left argument, as follows:
1 class Widget 2 { 3 public: 4 ... 5 Widget& operator=(const Widget& rhs) 6 { 7 ... 8 return *this; 9 } 10 ... 11 };
note:
This rule applies not only to the assignment =, other operators like + =, - =, etc. are equally applicable.
When you define a class, we explicitly or implicitly specifies the object of this type of copying, assignment and what to do when destroyed. Controlled by a class member functions defined in these three special operations are copy constructor , assignment operator and destructor .