TheValue assignment operator overload FunctionThe function is similar to that of the built-in value assignment operator. However, you must note that it is the same as the copy constructor and the destructor. Pay attention to the issue of deep copy and shallow copy, if you do not specify the default value assignment operator to overload a function without a deep copy, the system automatically provides a value assignment operator to overload the function.
The definition of the value assignment operator overload function is similar to that of another operator overload function.
The following example shows how to use it. The Code is as follows:
C ++ code
// Program Author: Guan Ning // Site: www.cndev-lab.com // All the manuscripts are copyrighted. If you want to reprint them, be sure to use the famous source and author.
# Include <iostream> Using namespace std;
Class Internet { Public: Internet (char * name, char * url) { Internet: name = new char [strlen (name) + 1]; Internet: url = new char [strlen (url) + 1]; If (name) { Strcpy (Internet: name, name ); } If (url) { Strcpy (Internet: url, url ); } } Internet (Internet & temp) { Internet: name = new char [strlen (temp. name) + 1]; Internet: url = new char [strlen (temp. url) + 1]; If (name) { Strcpy (Internet: name, temp. name ); } If (url) { Strcpy (Internet: url, temp. url ); } } ~ Internet () { Delete [] name; Delete [] url; } Internet & operator = (Internet & temp) // value assignment operator overload Function { Delete [] this-> name; Delete [] this-> url; This-> name = new char [strlen (temp. name) + 1]; This-> url = new char [strlen (temp. url) + 1]; If (this-> name) { Strcpy (this-> name, temp. name ); } If (this-> url) { Strcpy (this-> url, temp. url ); } Return * this; } Public: Char * name; Char * url; }; Int main () { Internet a ("China Software Development Lab", "www.cndev-lab.com "); Internet B = a; // The object B does not exist. Therefore, you can call the copy constructor to construct the constructor. Cout <B. name <endl <B. url <endl; Internet c ("American online", "www.aol.com "); B = c; // The B object already exists. Therefore, the system selects the value assignment operator to overload function processing. Cout <B. name <endl < |
|