This article only implements the constructor, destructor, assignment constructor and assignment function of the String class. Other operations will not be described in detail. The general written test interview will basically only require the realization of the functions of these four functions.
#include <iostream> using namespace std; class String { public : // Constructor String( const char *str= NULL); // Copy constructor String( const String& other); // Assignment function String& operator =( const String & other); // Destructor ~String( void ); private: char *data; }; String::String(const char * str) { if (str == NULL) { data = new char[1]; *data = '\0'; } else { int len = strlen (str) + 1 ; data = new char[len]; strcpy(data, str); } } String::String(const String& other) { int len = strlen(other.data) + 1; data = new char[len]; strcpy(data, other.data); } String & String:: operator =( const String& other) { // Determine whether it is self-assignment if ( this == & other) return * this ; delete[]data; int len = strlen(other) + 1; data = new char[len]; strcpy(data, other.data); // Return a reference to this object return * this ; } String::~String() { delete[]data; }