C ++Code
Class String
{
Public :
String ( Const Char * STR = NULL ); // Common Constructor
String ( Const String & other ); // Copy constructor
~ String ( Void ); // Destructor
String & operate = ( Const String & other ); // Value assignment function
Private :
Char * M_data; // Used to save strings
};
Compile the preceding four functions of string.
C ++ code
// Common Constructor
String: string ( Const Char * Str)
{
If (STR = NULL)
{
M_data = New Char [ 1 ]; // Score point: automatically apply to store the ending sign '\ 0' for an empty string // Extra points: determines if m_data is added with null
* 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 );
}
}
// String destructor
String ::~ String ( Void )
{
Delete [] m_data; // Or delete m_data;
}
// Copy constructor
String: string ( Const String & other) // Score point: the input parameter is of the const type.
{
Int Length = strlen (other. m_data );
M_data = New Char [Length + 1 ]; // Extra points: determines if m_data is added with null
Strcpy (m_data, other. m_data );
}
// Value assignment function
String & string: operate = ( Const String & other) // Score point: the input parameter is of the const type.
{
If ( This ==& Other) // Score point: Check auto-assigned values
Return * This ;
Delete [] m_data; // Score point: Release original memory resources
Int Length = strlen (other. m_data );
M_data = New Char [Length + 1 ]; // Extra points: determines if m_data is added with null
Strcpy (m_data, other. m_data );
Return * This ; // Score point: returns the reference of this object.
}
Analysis:
The interviewer who can accurately compile string class constructor, copy constructor, assign value function and destructor has at least 60% of the basic C ++ skills! This class includes the pointer class member variable m_data,When a class includes pointer class member variables, it must be overloaded to copy constructors, assign values, and destructor.ProgramBasic RequirementsIt is also a special clause in Objective C ++. Take a closer look at this class and pay special attention to the significance of adding comments to the score points and points. In this way, more than 60% of the basic C ++ skills are available!