類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 );
m_data = new char[length+1]; //對m_data加NULL 判斷
strcpy( m_data, other.m_data );
return *this; //返回本對象的引用
}
發佈了29 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章