如何用c语言实现CString的构造函数、析构函数和赋值函数?

编写类String的构造函数、析构函数和赋值函数  
  已知类String的原型为:  
  class     String  
  {  
  public:  
  String(const   char*str=NULL);//普通构造函数  
  String(const   String&other);         //拷贝构造函数  
  ~String(void);                                 //构析函数  
  String&operate=(const   String&other);         //赋值函数  
  Private:  
  Char       *m_data; //用于保存字符串  
  };  
  请编写String的上述4个函数。

String::String(const   char*str=NULL)  
  {  
  if(str   ==   NULL)  
  {  
  Init();  
  return   ;  
  }  
  int   nLen   =   SafeStrlen(str)   +   1;  
  if   (nLen   !=   1)  
  {  
  m_data   =   new   char[nLen];  
                                      memset(m_data,   0,   nLen);  
  memcpy(m_data,   lpsz,   nLen*sizeof(char));  
  }  
  else   Init();  
  }  
  String::String(const   String&other)  
  {  
          int   len   =   SafeStrlen(other.m_data)   +   1;  
          m_data   =   new   char[len];  
          memset(m_data,   0,   len);  
          memcpy(m_data,   other.m_data,   len);  
  }  
   
  String::~String()  
  //     free   any   attached   data  
  {  
  if(m_data)  
  delete   []m_data;  
  }  
   
  const   String&   String::operator=(const   String&   other)  
  {  
  char*   pOldData   =   m_data;  
  int   len   =   SafeStrlen(other.m_data)   +   1;  
  if(   len   !=   1   )  
  {  
  m_data   =   new   char[len];  
  memset(m_data,   0,   len);  
  memcpy(m_data,   other.m_data,   len);  
  if(pOldData)   delete[]pOldData;  
                                  return   *this;  
  }  
   
                  if(pOldData)   delete[]pOldData;  
                  Init();  
  return   *this;  
  }  
   
  void   String::Init()  
  {  
  m_data   =   new   char[1];    
  *m_data   =   '/0';  
  }  
   
  int   String::SafeStrlen(LPCTSTR   lpsz)  
  {    
  return   (lpsz   ==   NULL)   ?   0   :   strlen(lpsz);    
  }  

原文地址:https://www.cnblogs.com/wolflion/p/2539158.html