1 class mystring 2 { 3 private: 4 char *s; 5 static mystring *self; 6 public: 7 ~ mystring(); 8 const char *get_s() const; 9 const void set_s(const char *s); 10 static mystring *makestring(const char *s = NULL); 11 static void deletestring(); 12 protected: 13 mystring(); 14 mystring(const mystring &it); //构造函数 15 mystring(const char *s); 16 17 }; 18 19 mystring *mystring::self = NULL; 20 21 mystring::mystring():s(NULL) 22 { 23 24 } 25 26 mystring::mystring(const char *s) 27 { 28 int len = strlen(s); 29 this->s = new char[len +1]; 30 strcpy(this->s,s); 31 this->s[len] = 0; 32 } 33 34 35 mystring::mystring(const mystring &it) //通过拷贝构造函数实现深拷贝 36 { 37 int len = strlen(it.get_s()); 38 this->s = new char[len +1]; 39 strcpy(this->s, it.s); 40 this->s[len] = 0; 41 } 42 43 mystring::~mystring() 44 { 45 delete s; 46 s = NULL; 47 } 48 49 const char *mystring::get_s() const 50 { 51 return s; 52 } 53 54 const void mystring::set_s(const char *s) 55 { 56 if(this->s == NULL) 57 { 58 int len = strlen(s); 59 this->s = new char[len +1]; 60 strcpy(this->s, s); 61 this->s[len] = 0; 62 } 63 else 64 { 65 int len1 = strlen(this->s); 66 int len2 = strlen(s); 67 if(len1 >= len2) 68 { 69 strcpy(this->s, s); 70 this->s[len2] = 0; 71 } 72 else 73 { 74 delete []this->s; 75 this->s = new char[len2+1]; 76 strcpy(this->s, s); 77 this->s[len2] = 0; 78 } 79 } 80 } 81 82 mystring *mystring::makestring(const char *s) 83 { 84 if(self == NULL) 85 { 86 if(s == NULL) 87 { 88 self = new mystring; 89 } 90 else 91 { 92 self = new mystring(s); 93 } 94 } 95 return self; 96 } 97 98 void mystring::deletestring() 99 { 100 if(self != NULL) 101 { 102 delete self; 103 self = NULL; 104 } 105 106 }