构造函数

 下面不太完美,if(m_data)delete [] m_data;if(m_data==NULL)return *this;

  1. class String  
  2. {  
  3.     public:  
  4.     String(const char *str=NULL);  
  5.     String(const String& other);  
  6.     String& operator=(const String& other);  
  7.     ~String();  
  8.     private:  
  9.     char *m_data;  
  10. };  
  11. String::String(const char* str)  
  12. {  
  13.     if(str==NULL)  
  14.     {  
  15.         m_data=new char[1];  
  16.         *m_data='';  
  17.     }  
  18.     else  
  19.     {  
  20.         int length=strlen(sizeof(str));  
  21.         m_data=new char[length+1];  
  22.         strcpy(m_data, str);  
  23.     }  
  24. }  
  25. String::String(const String &other)  
  26. {  
  27.     int length=strlen(other.m_data);  
  28.     m_data=new char[length+1];  
  29.     strcpy(m_data, other.m_data);  
  30. }  
  31. String& operator=(const String& other)  
  32. {  
  33.     if(this==&other)  
  34.         return *this;  
  35.     delete []m_data;  
  36.     int length = strlen(other.m_data);  
  37.     m_data=new char[length+1];  
  38.     strcpy(m_data, other.m_data);  
  39.     return *this;  
  40. }  
  41. ~String()  
  42. {  
  43.     delete []m_data;  
  44. }  
原文地址:https://www.cnblogs.com/dobben/p/7500298.html