C++笔试题 String类的实现

来源:互联网 发布:mac系统iso镜像下载 编辑:程序博客网 时间:2024/06/05 17:42

转自:点击打开链接

这个在面试或笔试的时候常问到或考到。

已知类String的原型为:
[cpp] view plain copy
  1. class String  
  2. {  
  3. public:  
  4.      String(const char *str = NULL);// 普通构造函数  
  5.      String(const String &other);    // 拷贝构造函数  
  6.      ~ String(void);    // 析构函数  
  7.      String & operate =(const String &other);// 赋值函数  
  8. private:  
  9.      char *m_data;// 用于保存字符串  
  10. };   

请编写String的上述4个函数。

[cpp] view plain copy
  1. //普通构造函数  
  2. String::String(const char *str)  
  3. {  
  4.         if(str==NULL)  
  5.         {  
  6.                 m_data = new char[1]; // 得分点:对空字符串自动申请存放结束标志'\0'的//加分点:对m_data加NULL 判断  
  7.                 *m_data = '\0';  
  8.         }      
  9.         else  
  10.         {  
  11.          int length = strlen(str);  
  12.          m_data = new char[length+1]; // 若能加 NULL 判断则更好  
  13.          strcpy(m_data, str);  
  14.         }  
  15. }   
  16.   
  17. // String的析构函数  
  18. String::~String(void)  
  19. {  
  20.         delete [] m_data; // 或delete m_data;  
  21. }  
  22.   
  23. //拷贝构造函数  
  24. String::String(const String &other)    // 得分点:输入参数为const型  
  25. {       
  26.         int length = strlen(other.m_data);  
  27.         m_data = new char[length+1];     //加分点:对m_data加NULL 判断  
  28.         strcpy(m_data, other.m_data);      
  29. }   
  30.   
  31. //赋值函数  
  32. String & String::operate =(const String &other) // 得分点:输入参数为const型  
  33. {       
  34.         if(this == &other)                    //得分点:检查自赋值  
  35.                 return *thisdelete [] m_data;     //得分点:释放原有的内存资源  
  36.         int length = strlen( other.m_data );        
  37.         m_data = new char[length+1];  //加分点:对m_data加NULL 判断  
  38.         strcpy( m_data, other.m_data );     
  39.         return *this;             //得分点:返回本对象的引用    
  40. }  

剖析:

能够准确无误地编写出String类的构造函数、拷贝构造函数、赋值函数和析构函数的面试者至少已经具备了C++基本功的60%以上!
在这个类中包括了指针类成员变量m_data,当类中包括指针类成员变量时,一定要重载其拷贝构造函数、赋值函数和析构函数,这既是对C
++程序员的基本要求,也是《Effective C++》中特别强调的条款。

仔细学习这个类,特别注意加注释的得分点和加分点的意义,这样就具备了60%以上的C++基本功!

原创粉丝点击