Assignment and replication of an object: assignment: Overloading with the "=" operator
User A (ten), B;
b = A;
Replication: Calling the copy constructor
User A (b);
User A = b;//equivalent to User A (b);
In contrast to assignment, the assignment is to assign a value to an already existing object (an object that has already been assigned is defined), and replication creates a new object from scratch and makes it the same as an existing object.
Shallow copy and deep copy: If there is a pointer member in the object, the address of the pointer member is copied only to the newly created object, so the pointer members in two objects point to the same chunk of memory, and the issue of duplicate release occurs when it is released. You need to manually define a copy constructor, in which new memory is allocated for pointer variables, and pointer members of different objects point to different memory regions.
Use the copy constructor three cases: 1, need to create a new object, and another similar object to initialize it 2, the function parameter is the object of the class, when calling the function need to establish a copy of the argument, according to the actual parameter to copy a formal parameter, the system is to call the copy constructor implementation of 3, The return value of the function is the object of the class: At the end of the function call, you need to copy the object in the function to a temporary object and pass it to the call of the function.
The code is as follows:
User GetUser ()
int main ()
User user = GetUser ();//Call GetUser ();
At the end of the GetUser () function call, the lifetime of the object created in GetUser ends (is about to be destroyed), so instead of bringing temp back to main, instead of calling the copy constructor of the user class while executing the return statement, a new, object is copied by temp, It is then assigned to the user.
http://www.bkjia.com/PHPjc/325801.html www.bkjia.com true http://www.bkjia.com/PHPjc/325801.html techarticle assignment and replication of objects: assigning: Overloading User A (ten) with the "=" operator, B; b = A; Copy: Call the copy constructor User B; User A (b); or User A = b;//equivalent to User A (b); ....