class string
{
public:
string(const char *str ); // 通用構造函數
string(const string &another); // 拷貝構造函數
~ string(); // 析構函數
string & operater =(const string &rhs); // 指派函數
private:
char *m_data; // 用于儲存字元串
};
嘗試寫出類的成員函數實作。
答案:
string::string(const char *str)
if ( str == null ) //strlen在參數為null時會抛異常才會有這步判斷
m_data = new char[1] ;
m_data[0] = '/0' ;
}
else
m_data = new char[strlen(str) + 1];
strcpy(m_data,str);
string::string(const string &another)
m_data = new char[strlen(another.m_data) + 1];
strcpy(m_data,other.m_data);
string& string::operator =(const string &rhs)
if ( this == &rhs)
return *this ;
delete []m_data; //删除原來的資料,新開一塊記憶體
m_data = new char[strlen(rhs.m_data) + 1];
strcpy(m_data,rhs.m_data);
string::~string()
delete []m_data ;