1.实现一个string类

 

《剑指offer》系列---1

分类: 笔试面试   66人阅读  评论(0)  收藏  举报

最近一直在看剑指offer,这上面的题目都是比较考察编程能力的,打算做个记录,把写过的代码保存下来:

1.实现一个string类

面试官的考察点应该在以下几点:

1.模板类的书写

2.对于赋值函数考察的几点:(1)是否返回引用,因为只有返回引用,才能连续的进行赋值 (2)参数是否是常量 (3)是否是自身赋值(4)是否释放原来的内存 

一个完善的 string类如下:

[cpp]  view plain copy
  1. #include <iostream>  
  2. #include <cstring>  
  3. using namespace std;  
  4.   
  5. class String  
  6. {  
  7. public:  
  8.     String(const char *s = NULL);  
  9.     String(const String &rhs);  
  10.     String &operator=(const String &rhs);  
  11.     ~String();  
  12.     friend ostream& operator<<(ostream &os, String&str);  
  13. private:  
  14.     char *m_data;  
  15. };  
  16.   
  17. String::String(const char *str)  
  18. {  
  19.     if(str == NULL)  
  20.         m_data = NULL;  
  21.     else  
  22.     {  
  23.         int len = strlen(str);  
  24.         m_data = new char [len+1];  
  25.         strcpy(m_data, str);  
  26.     }  
  27. }  
  28. String::String(const String &rhs)  
  29. {  
  30.     if(rhs.m_data == NULL)  
  31.         m_data == NULL;  
  32.     else  
  33.     {  
  34.         int len = strlen(rhs.m_data);  
  35.         m_data = new char [len+1];  
  36.         strcpy(m_data, rhs.m_data);  
  37.     }  
  38. }  
  39.   
  40. String::~String()  
  41. {  
  42.     delete[] m_data;  
  43.     m_data = NULL;  
  44. }  
  45.   
  46. String& String::operator=(const String &rhs)  
  47. {  
  48.     /*if(&rhs == this) 
  49.         return *this; 
  50.     else 
  51.     { 
  52.         delete[] m_data; 
  53.         int len = strlen(rhs.m_data); 
  54.         m_data = new char [len+1]; 
  55.         strcpy(m_data, rhs.m_data); 
  56.     } 
  57.     return *this;*/  
  58.     //摘自《剑指offer》  
  59.     if(&rhs != this)  
  60.     {  
  61.         String temp(rhs);  
  62.         char *t;  
  63.         t = m_data;  
  64.         m_data = temp.m_data;  
  65.         temp.m_data = t;  
  66.     }  
  67.     return *this;  
  68. }  
  69. ostream &operator<<(ostream &os, String &str)  
  70. {  
  71.     os<<str.m_data;  
  72.     return os;  
  73. }  
  74. int main()  
  75. {  
  76.     String obj1("12");  
  77.     String obj2(obj1);  
  78.     String obj3, obj4;  
  79.     obj4 = obj3 = obj2;  
  80.     cout<<obj1<<endl;  
  81.     cout<<obj2<<endl;  
  82.     cout<<obj3<<endl;  
  83.     cout<<obj4<<endl;  
  84.     return 0;  
  85. }  

对于赋值操作符,如果我们在delete之后,new失败了怎么办,这不是异常安全的,所以<<剑指offer>>中给了我
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值