标签:
<span style="font-size:18px;">class CMyString { public: CMyString() :str(new char[1]) { str[0] = '\0'; } CMyString(char* _str) :str(new char[strlen(_str)+1]) { strcpy(str, _str); } CMyString(CMyString& s) :str(NULL) { delete[] str; str = new char[strlen(s.str) + 1]; strcpy(str, s.str); } CMyString& operator=(CMyString& s) { if (this != &s) { delete[] str; str = new char[strlen(s.str) + 1]; strcpy(str, s.str); } return *this; } ~CMyString() { if (str) { delete[] str; str = NULL; } } friend ostream& operator<<(ostream& os,CMyString& s) { os << s.str; return os; } private: char* str; };</span>
<span style="font-size:18px;">class CMyString { private: void Release() { if (str && --GetCount(str) == 0) { delete[](str - 4); str = NULL; } } int& GetCount(char* str) { return (*(int*)(str - 4)); } public: CMyString(char* _str = "") :str(new char[strlen(_str) + 5]) { *(int*)str = 1; str += 4; strcpy(str, _str); } CMyString(const CMyString& s) :str(s.str) { ++GetCount(str); } CMyString& operator=(const CMyString& s) { if (this != &s) { Release(); str = s.str; ++GetCount(str); } return *this; } //写时拷贝 char& operator[](size_t index) { if (GetCount(str) > 1) { --GetCount(str); char* tmp = new char[strlen(str) + 5]; tmp += 4; GetCount(tmp) = 1; strcpy(tmp, str); str = tmp; } return str[index]; } ~CMyString() { Release(); } friend ostream& operator<<(ostream& os, CMyString& s) { os << s.str; return os; } private: char* str; };</span>
int main() { CMyString s1("hello"); CMyString s2; s2 = s1; CMyString s3 = s1; cout << s1 << endl; cout << s2 << endl; cout << s3 << endl; //浅拷贝中的写时拷贝测试用例 s3[0] = 'b'; s3[1] = 'l'; s3[2] = 'k'; cout << s3 << endl; return 0; }
标签:
原文地址:http://blog.csdn.net/kkmdmcgxi/article/details/51347605