This is often asked or tested during an interview or written test.
The prototype for the known class string is:
Class string
{public
:
string (const char *STR = NULL);//Normal constructor
string (const string &other); Copy constructor
~string (void);/destructor
string & operator = (const string &other);//Assignment Function
private:
Char *m _data;//is used to save the string
};
Please write the above 4 functions of string.
Normal constructor
string::string (const char *str)
{
if (str = NULL)
{
m_data = new char[1];// Score points: Automatically apply to empty strings to store the end of the flag ' ", plus points: the m_data plus null to judge
*m_data = '"
;}
else
{
int length = strlen (str);
m_data = new Char[length + 1];//better
strcpy (m_data, str) If you can add NULL;
The destructor of String
string::~string (void)
{
delete[] m_data;//or delete m_data;
}
Copy constructor
string::string (const String &other)//score points: The input parameter is a const type
{
int length = strlen (other.m_data );
m_data = new Char[length + 1];//better
strcpy (m_data, other.m_data) If it can be added with NULL
;
Assignment function
string & string::operator = (const string &other)//score point: The input parameter is a const type
{
if (this = = &oth ER)//score point: Check the value of return
*this;
if (m_data)
delete[] m_data;//score point: Frees the original memory resource
int length = strlen (other.m_data);
m_data = new Char[length + 1];//plus points: m_data plus null to Judge
strcpy (M_data, other.m_data);
Return *this;//score point: Returns a reference to this object
}
Analysis: The interviewer who can accurately write the constructors of string classes, copy constructors, assignment functions and destructors has at least 60% of the basic skills of C + +.
In this class include the pointer class member variable m_data, when the class includes pointer class member variable, must overload its copy constructors, assignment functions and destructors, this is both the basic requirements of C + + programmers, but also "effective C + +" Special emphasis on the terms.
Carefully learn this class, pay special attention to the point of scoring points and add points of significance, so that have more than 60% of C + + basic skills.
Original link: http://www.cnblogs.com/jwyue0520/archive/2012/12/03/2800160.html