天天看點

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++基本功!

原文:

http://baike.baidu.com/view/3369697.htm

繼續閱讀