这些小活动你都参加了吗?快来围观一下吧!>>
电子产品世界 » 论坛首页 » 嵌入式开发 » STM32 » C++面试中经常会让手写String类的实现

共2条 1/1 1 跳转至

C++面试中经常会让手写String类的实现

高工
2018-01-28 12:23:21     打赏

主要是完成String类的构造函数、拷贝构造函数、赋值构造函数和析构函数。这个类中包括了指针类成员变量m_data,当类中包括指针类成员变量时,一定要重载构造函数、赋值函数、析构函数;

下面是具体的实现:


[cpp] view plain copy
  1. class String  

  2. {  

  3. public:  

  4.     String(const char* str=NULL);//普通的构造函数  

  5.     String(const String& other); //拷贝构造函数  

  6.     ~String();  

  7.     String& operate = (const String& other);//复制构造  

  8. private:  

  9.     char* m_data;//用于保存字符串  

  10. };  

  11.   

  12. String::String(const char* str)  

  13. {  

  14.     if (str==NULL)  

  15.     {  

  16.         m_data = new char[1];  

  17.         *m_data = '\0';  

  18.     }  

  19.     else  

  20.     {  

  21.         int len = strlen(str);  

  22.         m_data = new char[len+1];  

  23.         strcpy(m_data, str);  

  24.     }  

  25. }  

  26.   

  27. String::~String()  

  28. {  

  29.     if (m_data!=NULL)  

  30.     {  

  31.         delete[] m_data;  

  32.         m_data = NULL;  

  33.     }  

  34. }  

  35.   

  36. String::String(const String & other)  

  37. {  

  38.     int len = strlen(other.m_data);  

  39.     m_data = new char[len + 1];  

  40.     strcpy(m_data, other.m_data);  

  41. }  

  42.   

  43. String& String::operate = (const String & other)  

  44. {  

  45.     if (this==other)  

  46.     {  

  47.         return *this;  

  48.     }  

  49.     delete[] m_data;  

  50.     int len = strlen(other.m_data);  

  51.     m_data = new char[len + 1];  

  52.     strcpy(m_data, other.m_data);  

  53.     return *this;  




专家
2018-01-29 12:31:21     打赏
2楼

不错的入门知识。


共2条 1/1 1 跳转至

回复

匿名不能发帖!请先 [ 登陆 注册 ]