String 类的函数实现
1 #include<iostream> 2 //#include<string> 3 using namespace std; 4 5 class Strings 6 { 7 public: 8 Strings(const char * str=NULL); 9 10 Strings(const Strings &another); 11 ~Strings(); 12 Strings & operator=(const Strings &ths); 13 private: 14 char *m_data; 15 }; 16 Strings::Strings(const char *str) 17 { 18 if(str==NULL) 19 { 20 m_data=new char[1]; 21 m_data[0]='\0'; 22 } 23 else 24 { 25 m_data=new char[strlen(str)+1]; 26 strcpy(m_data,str); 27 } 28 29 } 30 Strings::Strings(const Strings &another) 31 { 32 m_data=new char[strlen(another.m_data)+1]; 33 strcpy(m_data,another.m_data ); 34 } 35 Strings::~Strings() 36 { 37 delete [] m_data; 38 } 39 40 Strings &Strings::operator=(const Strings &ths) 41 { 42 if(this==&ths) 43 return *this; 44 delete[]m_data; 45 m_data=new char[strlen(ths.m_data)+1]; 46 strcpy(m_data,ths.m_data); 47 return *this; 48 } 49 int main() 50 { 51 Strings a("abcdefg"); 52 printf("%s\n",a); 53 Strings b(a); 54 printf("%s\n",b); 55 Strings c=b; 56 printf("%s\n",c); 57 system("pause"); 58 return 0; 59 60 }