Home  >  Article  >  Backend Development  >  Copy constructor and assignment operator overloading in php_PHP tutorial

Copy constructor and assignment operator overloading in php_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:17:07860browse

Assignment and copying of objects: Assignment: overloaded through the "=" operator
User a(10),b;
b = a;
Copy: call the copy constructor
User b;
User a(b);
or
User a = b;//Equivalent to the difference between User a(b);
and assignment. Assignment is to assign a value to an existing object (already implemented definition (the assigned object), while copying creates a new object from scratch and makes it the same as the existing object.
Shallow copy and deep copy: If there is a pointer member in the object, only the address of the pointer member will be copied to the newly created object. Therefore, the pointer members in both objects point to the same memory. Area, there will be repeated release problems when releasing. You need to manually define a copy constructor. In the constructor, new memory will be allocated for pointer variables. The pointer members of different objects point to different memory areas.
Three situations when the copy constructor is used: 1. You need to create a new object and initialize it with another object of the same type. 2. When the parameter of the function is an object of the class, you need to create an actual parameter when calling the function. Copy, copy a formal parameter according to the actual parameter, the system is implemented by calling the copy constructor 3. The return value of the function is the object of the class: At the end of the function call, the object in the function needs to be copied to a temporary object and passed to The calling point of this function.

Copy code The code is as follows:

User getUser()
{
User temp;
return temp;
}
int main()
{
User user = getUser();//Call getUser();
}

getUser() When the function call ends, the life cycle of the object temp created in getUser ends (will be destroyed), so instead of bringing temp back to main, when executing the return statement, call the copy constructor of the User class and copy a new one according to temp , object, and then assign it to user.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/325801.htmlTechArticleAssignment and copying of objects: Assignment: Overloading User a(10),b; b = through the "=" operator a; Copy: Call the copy constructor User b; User a(b); or User a = b;//Equivalent to User a(b);...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn