Class String
{
Public
Common constructors
String (const char *STR = NULL)
{
if (str = = NULL)
{
m_data = new Char[1];
*m_data = ' + ';
}
Else
{
m_data = new Char[strlen (str) + 1];
strcpy (m_data, str);
}
}
Copy constructor
String (const string &s)
{
m_data = new Char[strlen (s) + 1];
strcpy (M_data, s.m_data);
}
Assignment operator overloading
String & operator= (const string &s)
{
if (this = = &s)
{
return *this;
}
delete [] m_data;
m_data = new Char[strlen (s.m_data) + 1];
strcpy (M_data, s.m_data);
return *this;
}
Destructors
~string ()
{
if (m_data! = NULL)
{
delete [] m_data;
m_data = NULL;
}
}
Private
Char *m_data;
}
For assignment operator overloading there are three points to note:
The return value should be a reference to increase efficiency, or the return value will generate a temporary copy.
Second, the parameters should be applied, for a reason.
The parameter is set to the const type, preventing parameters from being modified inside the function.
C + + String class (construction, copy construction, assignment operator overloading, and destructor)