1 #include<stdio.h> 2 #include<assert.h> 3 4 class MyString 5 { 6 public: 7 MyString() 8 { 9 _data = new char[1]; 10 _data = ‘\0‘; 11 } 12 13 MyString(char* str) 14 { 15 assert(str); 16 _data = new char[strlen(str) + 1]; 17 strcpy(_data, str); 18 } 19 20 MyString(const MyString& string) 21 { 22 assert(string._data); 23 _data = new char[strlen(string._data) + 1]; 24 strcpy(_data, string._data); 25 } 26 27 ~MyString() 28 { 29 delete[] _data; 30 } 31 32 MyString& operator= (const MyString& string) 33 { 34 assert(string._data); 35 if(*this == string) 36 { 37 return *this; 38 } 39 40 delete[] _data; 41 _data = NULL; 42 _data = new char[strlen(string._data) + 1]; 43 strcpy(_data, string._data); 44 return *this; 45 } 46 47 protected: 48 char* _str; 49 }
1 #include<stdio.h> 2 #include<assert.h> 3 4 class MyString 5 { 6 public: 7 MyString() 8 { 9 _data = new char[1]; 10 _data = ‘\0‘; 11 } 12 13 MyString(char* str) 14 { 15 assert(str); 16 _data = new char[strlen(str) + 1]; 17 strcpy(_data, str); 18 } 19 20 MyString(const MyString& string) 21 { 22 assert(string._data); 23 _data = new char[strlen(string._data) + 1]; 24 strcpy(_data, string._data); 25 } 26 27 ~MyString() 28 { 29 delete[] _data; 30 } 31 32 MyString& operator= (const MyString& string) 33 { 34 assert(string._data); 35 if(*this != string) 36 { 37 MyString tem(string); 38 39 char* del = tem._data 40 tem._data = _data; 41 _data = del; 42 } 43 return *this; 44 } 45 46 protected: 47 char* _str; 48 }
本文出自 “水仙花” 博客,请务必保留此出处http://10704527.blog.51cto.com/10694527/1783629
原文地址:http://10704527.blog.51cto.com/10694527/1783629