Compile the constructor, destructor, and value assignment functions of the string class. The prototype of the known string class is:
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) // 6 points { If (STR = Null) {m_data = New Char [ 1 ]; // It is better if null can be added. * M_data = '\ 0 ';} Else { Int Length = Strlen (STR); m_data = New Char [Length +1 ]; // It is better if null can be added. Strcpy (m_data, STR );}}
// Copy constructor String: string ( Const String & other)
{ Int Length = Strlen (other. m_data); m_data = New Char [Length + 1 ];// It is better if null can be added. Strcpy (m_data, other. m_data );}
// Value assignment function String & string: operate = ( Const String & other)
{ // (1) Check auto-assigned values
If ( This == & Other) Return *This ; // (2) Release original memory resources
Delete [] m_data; // (3) allocate new memory resources and copy the content
Int Length = Strlen (other. m_data); m_data = New Char [Length + 1 ]; // It is better if null can be added. Strcpy (m_data, other. m_data ); // (4) return the reference of this object
Return * This ;}
//String destructor
String ::~ String (Void){
Delete [] m_data;
//Because m_data is an internal data type, you can also write it as delete m_data;
}
The C standard library contains the string Library: String. h contains strlen (), strcpy () functions, and so on.
C-style string library in C ++: # include <cstring>
Extended string library in C ++: # include <string>