天天看點

String類

已知類string的原型為:

class string

{

public:

string(const char *str = null);// 普通構造函數

string(const string &other); // 拷貝構造函數

~ string(void); // 析構函數

string & operator =(const string &other);// 指派函數

private:

char *m_data;// 用于儲存字元串

};

請編寫string的上述4個函數。

//普通構造函數

string::string(const char *str)

if(str==null)

m_data = new char[1]; // 對空字元串自動申請存放結束标志'\0'的

//加分點:對m_data加null 判斷

*m_data = '\0';

}

else

int length = strlen(str);

m_data = new char[length+1]; // 若能加 null 判斷則更好

strcpy(m_data, str);

// string的析構函數

string::~string(void)

delete[] m_data; // 或delete m_data;

//拷貝構造函數

string::string(const string &other) // 輸入參數為const型

int length = strlen(other.m_data);

m_data = new char[length+1]; //對m_data加null 判斷

strcpy(m_data, other.m_data);

//指派函數

string & string::operator =(const string &other) // 輸入參數為const

if(this == &other) //檢查自指派

return *this;

delete[] m_data; //釋放原有的記憶體資源

int length = strlen( other.m_data );

strcpy( m_data, other.m_data );

return *this; //傳回本對象的引用

剖析:

能夠準确無誤地編寫出string類的構造函數、拷貝構造函數、指派函數和析構函數的面試者至少已經具備了c++基本功的60%以上!在這個類中包括了指針類成員變量m_data,當類中包括指針類成員變量時,一定要重載其拷貝構造函數、指派函數和析構函數,這既是對c++程式員的基本要求,也是《effective c++》中特别強調的條款。仔細學習這個類,特别注意加注釋的得分點和加分點的意義,這樣就具備了60%以上的c++基本功!

繼續閱讀