This article introduces in detail the copy constructor in PHP, the assignment operator overload of the detailed, there is need to understand the students can refer to the next OH.
Assignment and replication of an object: assignment: Overloading with the "=" operator
The code is as follows |
Copy Code |
User A (ten), B; b = A; Replication: Calling the copy constructor User b; User A (b); Or 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 |
Copy Code |
User GetUser () { User temp; return temp; } 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/629095.html www.bkjia.com true http://www.bkjia.com/PHPjc/629095.html techarticle This article introduces in detail the copy constructor in PHP, the assignment operator overload of the detailed, there is need to understand the students can refer to the next OH. Assignment and replication of an object: assignment: By ...