Requirements:
Write a string class, construct, copy, assign values, deconstruct, and so on.
Class string
{
Public:
String (const char * STR = NULL); // common Constructor
String (const string & other); // copy the constructor
~ String (void); // destructor
String & operate = (const string & other); // value assignment function
PRIVATE:
Char * m_data; // used to save strings
};
// String Constructor
String: string (const char * Str)
{
If (STR = NULL)
{
M_data = new char [1];
* M_data = '\ 0 ';
}
Else
{
Int length = strlen (STR );
M_data = new char [Length + 1];
Strcpy (m_data, STR );
}
}
// String destructor
String ::~ String (void)
{
Delete [] m_data;
// Because m_data is an internal data type, it can also be written as delete m_data;
}
// Copy the constructor
String: string (const string & other)
{
// Allow the operation of the private member m_data of other
Int length = strlen (other. m_data );
M_data = new char [Length + 1];
Strcpy (m_data, other. m_data );
}
// Value assignment function
String & string: operate = (const string & other)
{
// (1) Check the auto-assigned Value
If (this = & other)
Return * this;
// (2) release the original memory resource
Delete [] m_data;
// (3) allocate new memory resources and copy the content
Int length = strlen (other. m_data );
M_data = new char [Length + 1];
Strcpy (m_data, other. m_data );
// (4) return the reference of this object
Return * This; // remember at valid tive C ++, always return refrence of this.
}