String类实现

  1. class String{  
  2.     friend ostream& operator<< (ostream&,String&);  
  3. public:  
  4.     String(const char* str=NULL);                //...........(char)  
  5.     String(const String &other);                 //......(String)  
  6.     String& operator=(const String &other);       //operator=  
  7.     String operator+(const String &other)const; //operator+  
  8.     bool operator==(const String&);              //operator==  
  9.     char& operator[](unsigned int);              //operator[]  
  10.     size_t size(){return strlen(m_data);};  
  11.     ~String(void) {delete[] m_data;}  
  12. private:  
  13.     char *m_data;  
  14. };  
  15. inline String::String(const char* str)  
  16. {  
  17.     if (!str) m_data=0;  
  18.     else  
  19.     {  
  20.         m_data = new char[strlen(str)+1];  
  21.         strcpy(m_data,str);  
  22.     }  
  23. }  
  24. inline String::String(const String& other)  
  25. {  
  26.     if(!other.m_data) m_data=0;  
  27.     else  
  28.     {  
  29.         m_data=new char[strlen(other.m_data)+1];  
  30.         strcpy(m_data,other.m_data);  
  31.     }  
  32. }  
  33. inline String& String::operator=(const String& other)  
  34. {  
  35.     if (this!=&other)  
  36.     {  
  37.         delete[] m_data;  
  38.         if(!other.m_data) m_data=0;  
  39.         else  
  40.         {  
  41.             m_data = new char[strlen(other.m_data)+1];  
  42.             strcpy(m_data,other.m_data);  
  43.         }  
  44.     }  
  45.     return *this;  
  46. }  
  47. inline String String::operator+(const String &other)const  
  48. {  
  49.     String newString;  
  50.     if(!other.m_data)  
  51.         newString = *this;  
  52.     else if(!m_data)  
  53.         newString = other;  
  54.     else  
  55.     {  
  56.         newString.m_data = new char[strlen(m_data)+strlen(other.m_data)+1];  
  57.         strcpy(newString.m_data,m_data);  
  58.         strcat(newString.m_data,other.m_data);  
  59.     }  
  60.     return newString;  
  61. }  
  62. inline bool String::operator==(const String &s)  
  63. {  
  64.     if ( strlen(s.m_data) != strlen(m_data) )  
  65.         return false;  
  66.     return strcmp(m_data,s.m_data)?false:true;  
  67. }  
  68. inline char& String::operator[](unsigned int e)  
  69. {  
  70.     if (e>=0&&e<=strlen(m_data))  
  71.         return m_data[e];  
  72. }  
  73. ostream& operator<<(ostream& os,String& str)  
  74. {  
  75.     os << str.m_data;  
  76.     return os;  
  77. }  
  78. void main()  
  79. {  
  80.     String str1="Hello!";  
  81.     String str2="Teacher!";  
  82.     String str3 = str1+str2;  
  83.     cout<<str3<<"/n"<<str3.size()<<endl;  
  84.     system("pause");  
  85. }  

猜你喜欢

转载自blog.csdn.net/u010803748/article/details/81183742