// Write the constructor, destructor, and assignment functions for the String class.

 

class String

{

public:

String(const char *str = NULL); // The normal constructor

String(const String &other); // Copy the constructor

~String(void); // destructor

String & operator =(const String &other); // The assignment function

private:

char *m_data; // Used to save strings

};

 

/ / The normal constructor

String::String(const char *str)

{

if (str == NULL)

{

m_data = new char[1]; // Automatically request empty string to store the end flag ‘\0’ empty

// add NULL to m_data

*m_data = ‘\0’;

}

else

{

int length = strlen(str);

m_data = new char[length + 1]; // If you can add NULL judgment, it is better

strcpy(m_data, str);

}

}

\

// The destructor for String

String::~String(void)

{

delete[] m_data; / / or delete m_data;

}

// Copy the constructor

String::String(const String &other) // The input parameter is const

{

int length = strlen(other.m_data);

m_data = new char[length + 1]; // add NULL to m_data

strcpy(m_data, other.m_data);

}

// The assignment function

String & String::operate = (const String &other) // The input parameter is const

{

If (this == &other) // check the self-assignment

return *this;

delete[] m_data; // Release the original memory resources

int length = strlen(other.m_data);

m_data = new char[length + 1]; // add NULL to m_data

strcpy(m_data, other.m_data);

return *this; // Returns a reference to this object

}

 

Candidates who can write String constructors, copy constructors, assignment functions, and destructors without error have at least 60% of basic C++ skills! This class contains the pointer member variable m_data. When using a pointer member variable, override the copy constructor, assignment, and destructor. This is a basic requirement of the C++ programmer, and is highlighted in EffectiveC++. Study this class carefully, paying special attention to the meaning of the annotated points and bonus points, and you will have more than 60% of the basic C++ skills!