The following points should be noted:
1. Whether to declare the return value type as a reference to that type, or not to make successive assignments
2. Whether the passed parameter is declared as a constant reference , if it is not a constant, there is no guarantee that the passed argument will not be modified, and if it is not a reference, the copy constructor is called once to affect the efficiency of the Code.
3. Determines whether the two operands that are assigned are the same instance .
4. Whether to delete the memory of the assigned object, otherwise a memory leak will occur.
The program code is as follows:
#include <iostream>#include<cstring>using namespacestd;classmystring{ Public: Mystring&operator=(ConstMystring &str); Mystring (Char*pdata=null)//constructors with default values{Data=pdata; } Mystring (ConstMystring &str)//copy Constructor{Data=Str.data; } ~mystring ()// Destructors { } voidShow () {cout<<data<<Endl; }Private: Char*data;}; Mystring&mystring::operator=(ConstMystring &str) { if(&str!= This)//If the &str==this does not have to be assigned a value { DeleteData//release the original space firstData=NULL; Data=New Char[Strlen (Str.data) +1];//initializing space for pointersstrcpy (Data,str.data);//Assign Value } return* This;}intMain () {Mystring str1 ("Hello"), str2;//declaring two classes of objectsstr1.show (); STR2=STR1;//calling a custom assignment methodstr2.show (); STR1=STR1;//assign yourself a valuestr1.show (); return 0;}
Overloaded assignment operators