Some time ago, Xu * of S2 went to a nuclear energy company to perform software testing and asked such a question when applying for a job.
Write the constructor of the string class, copy the constructor, destructor, and assign values.
This is a very classic C ++ development question, which is often used in the interview with C ++ programmers. But this time I am helpless, why? This is because after Xu * started the white box test.
# Include <iostream>
Using namespace STD;
Class string
{
Public:
String (const char * STR = NULL );
String (const string & other );
~ String (void );
String & operator = (const string & other );
PRIVATE:
Char * m_data;
};
String: string (const char * Str)
{
Cout <"constructor called" <Endl;
If (STR = NULL) // avoid a wild pointer, such as string B
// Pointer
{
M_data = new char [1];
* M_data = ''/0 '';
}
Else
{
Int length = strlen (STR );
M_data = new char [Length + 1];
Strcpy (m_data, STR );
}
}
String ::~ String (void)
{
Delete m_data;
Cout <"destructor called" <Endl;
}
String: string (const string & other)
{
Cout <"the value assignment constructor is called" <Endl;
Int length = strlen (other. m_data );
M_data = new char [Length + 1];
Strcpy (m_data, other. m_data );
}
String & string: Operator = (const string & other)
{
Cout <"the value assignment function is called" <Endl;
If (this = & Other) // you do not need to copy your own copy.
Return * this;
Delete m_data; // Delete the previous memory space pointed to by pointer variables in the assigned object to avoid
// Memory leakage
Int length = strlen (other. m_data); // calculates the length.
M_data = new char [Length + 1]; // request Space
Strcpy (m_data, other. m_data); // copy
Return * this;
}
Void main ()
{
String B; // call the constructor
String A ("hello"); // call the constructor
String C ("world"); // call the constructor
String d = A; // call the value assignment constructor, because a is used for initialization during object d creation.
D = C; // call the value assignment function after the overload
}
Because the class contains pointer variables, this topic involves deep copy and shallow copy during object creation and analysis, and also involves how to avoid Memory leakage.
I feel that this question has fully examined some basic skills of C ++. The best way to learn C ++ is to find some classic examples and then compare them with the compiler. This will definitely get twice the result with half the effort.
This question has been debugged and can be run directly.
Article Source: http://www.diybl.com/course/3_program/c++/cppsl/20071218/92698.html