MyString.h
class CMyString { public: // CMyString(void); ~CMyString(void);
CMyString(const char* str = NULL); CMyString(const CMyString & another); CMyString & Operator = (const CMyString & another); CMyString operator + (const CMyString & another); bool operator > (const CMyString & another); bool operator < (const CMyString & another); bool operator == (const CMyString & another); char& operator[](int idx); void dis();private: char* _str; }; MyString.cpp
// 默認構造器 CMyString::CMyString(const char* str) { if (NULL == str) { _str = new char[1]; *_str = ‘/0’; } else { int len = strlen(str); _str = new char[len + 1]; strcpy_s(_str, len + 1, str); } } // 拷貝構造器 CMyString::CMyString(const CMyString & another) { int len = strlen(another._str); _str = new char[len + 1]; strcpy_s(_str, len + 1, another._str); } // 析構函數 CMyString::~CMyString() { delete []_str; } // 賦值運算符重載 CMyString & CMyString::operator = (const CMyString & another) { // 自賦值,出現錯誤 if (this == &another) { return *this; } // 先刪除自己開辟的空間 delete []_str; int len = strlen(another._str); this->_str = new char[len + 1]; strcpy_s(this->_str, len + 1, another._str); return *this; } // 加法運算符重載 CMyString CMyString::operator + (const CMyString & another) { int len = strlen(this->_str) + strlen(another._str); CMyString str; delete []str._str; str._str = new char[len + 1]; memset(str._str,0,len + 1); int len1 = strlen(this->_str) + 1; strcat_s(str._str, len1, this->_str); // 源串長度 + 目標串長度 + 結束符 int len2 = strlen(this->_str) + strlen(another._str) + 1; strcat_s(str._str,len2, another._str); return str; } // ==關系運算符重載 bool CMyString::operator==(const CMyString &other) { if(strcmp(this->_str,other._str) == 0) return true; else return false; } // >關系運算符重載 bool CMyString::operator>(const CMyString &other) { if(strcmp(this->_str,other._str) > 0) return true; else return false; } // <運算符重載 bool CMyString::operator<(const CMyString &other) { if(strcmp(this->_str,other._str) < 0) return true; else return false; } // []運算符重載 char& CMyString::operator[](int idx) { return _str[idx]; } // 打印函數 void CMyString::dis() { using namespace std; for (size_t i = 0; i < strlen(this->_str); i++) { cout << _str[i]; } cout << endl; }
新聞熱點
疑難解答