C++簡單實現string類
阿新 • • 發佈:2019-01-23
面試經常會考到的型別,主要考的是幾個建構函式和過載運算子,簡單的實現一下
class CString { public: CString(); ~CString(); int Length()const{return m_len;} CString(const char * const str); CString(const CString &str); char &operator[](int index)const; CString &operator=(const CString & str); //字串輸出 friend ostream& operator<<(ostream &out, const CString &str) { out<<str.m_str; return out; } private: char *m_str; int m_len; }; //預設建構函式 CString::CString() { m_len = 0; m_str = new char[1]; *m_str = '\0'; } //解構函式 CString::~CString() { if (m_str != NULL) { delete[] m_str; m_str = 0; } m_len = 0; } //過載建構函式 CString::CString( const char * const str ) { if (str != NULL) { m_len = strlen(str); m_str = new char[m_len + 1]; for (int i = 0; i < m_len; i++) { m_str[i] = str[i]; } m_str[m_len] = '\0'; } } //複製建構函式實現深層拷貝 CString::CString( const CString &str ) { m_len = strlen(str.m_str); m_str = new char[m_len + 1]; for (int i = 0; i < m_len; i++) { m_str[i] = str[i]; } m_str[m_len] = '\0'; } //過載[]操作符 char &CString::operator[]( int index ) const { if (index > m_len) { return m_str[m_len]; } if (index < 0) { return m_str[0]; } return m_str[index]; } //過載=操作符,實現兩個物件賦值 CString & CString::operator=( const CString & str ) { //如果是自己對自己賦值,那直接返回自身 if (this == &str) { return *this; } //刪除舊的資料(=號左邊的物件資料) if (m_str != NULL) { delete[] m_str; } m_len = str.Length(); m_str = new char[m_len + 1]; for (int i = 0; i < m_len; i++) { m_str[i] = str[i]; } m_str[m_len] = '\0'; return *this; } int main() { //呼叫預設無參建構函式 CString c1; //呼叫帶參建構函式 CString c2("HelloWorld"); //呼叫複製建構函式、[]運算子過載函式 CString c3 = c2; //呼叫=運算子過載函式 c1 = c3; //呼叫<<運算子操作函式 cout<<c1<<" "<<c2<<" "<<c3<<endl; return 0; }