编写一个完整的CString类
1 //编写CString类 2 class CString 3 { 4 public: 5 //带参构造函数 6 CString(const char *pStr = NULL) 7 { 8 if(pStr == NULL) 9 { 10 pData = new char; 11 *pData = '\0'; 12 } 13 else 14 { 15 pData = new char[strlen(pStr)+1]; 16 assert(pData != NULL); 17 strcpy(pData, pStr); 18 } 19 } 20 21 //拷贝构造函数 22 CString(const CString &other) 23 { 24 pData = new char[strlen(other.pData)+1]; 25 assert(pData != NULL); 26 strcpy(pData, other.pData); 27 } 28 29 //操作符重载 30 CString& operator=(const CString &other) 31 { 32 if(&other == this) 33 { 34 CString strTemp(other); 35 36 char *pTemp = strTemp.pData; 37 strTemp.pData = pData; 38 pData = pTemp; 39 } 40 return *this; 41 } 42 43 //析构函数 44 ~CString () 45 { 46 if(!pData) 47 delete[] pData; 48 } 49 50 private: 51 char *pData; 52 };
浙公网安备 33010602011771号