dengnilikai

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

笔试时经常碰到的题目:

请编写STRING类的构造函数、析构函数和赋值函数

分析:

STRING类的私有对象就是一个char*,用来new出空间以存放字符串,而公有对象分别是这几个函数:

构造函数有两个,一个用char *来初始化,一个用另一个STIRNG类的对象实例来初始化

析构函数将new出的空间delete掉

赋值函数重载=操作符,也是将另一个STRING类的对象实例的字符串拷贝过来。

代码(注意注释的部分,另重载<<操作符是为了调试之用):

  1 #include <string.h>    //strlen()等函数需要这个C的头文件
  2 #include <iostream>
  3 using namespace std;
  4 
  5 /*构造函数有两个:
  6 a.参数为字符串,将字符串strcpy到m_data new出的空间中,另字符串为NULL时,strlen会COREDOWN,所以要判断一下
  7 b.参数为String类的对象,将other对象的m_data strcpy到m_data中,在other是本身时,strlen会COREDOWN,所以要if判断一下
  8 析构函数主要是将m_data空间释放,并将指针置为NULL
  9 赋值函数以另一个String对象为参数other,将other.data拷贝到m_data,另要注意自赋值时会把自己delete掉再strcpy,会出错,所以需要if判断*/
 10 class String
 11 {
 12     
 13     friend ostream & operator << (ostream &os, const String &ob);    //cout时候要重载操作符<<
 14 public:
 15     String(const char *str);    //注意加const
 16     String(const String &other);    //注意加const
 17     ~String();
 18     String & operator = (const String &other);    //注意加const
 19 private:
 20     char *m_data;
 21 };
 22 
 23 String::String(const char *str)
 24 {
 25     int length = 0;
 26 
 27     /*str为NULL时strlen会段错误,所以要分开写*/
 28     if(str==NULL)
 29     {
 30         m_data = new char[1];
 31         *m_data = '\0';
 32     }else{
 33         length = strlen(str);
 34         m_data = new char[length+1];
 35         strcpy(m_data, str);
 36     }
 37 }
 38 
 39 String::String(const String &other)
 40 {
 41     int length = 0;
 42     /*为本身时strlen会引起段错误*/
 43     if(this!=&other)
 44         length = strlen(other.m_data);
 45     m_data = new char[length+1];
 46     strcpy(m_data, other.m_data);
 47 }
 48 
 49 String::~String()
 50 {
 51     delete [] m_data;
 52     m_data=NULL;    /*防止野指针*/
 53 }
 54 
 55 String & String::operator=(const String &other)    
 56 {
 57     int length = strlen(other.m_data);
 58     /*other为本身时会把自己的m_date delete掉再strcpy,这样是不对的*/
 59     if(this!=&other)
 60     {
 61         delete []m_data;
 62         m_data = new char[length+1];
 63         strcpy(m_data, other.m_data);
 64     }
 65     return *this;
 66 }
 67 
 68 /*另一种写法*/
 69 /*
 70 String & String::operator=(const String &other)
 71 {
 72     int length = strlen(other.m_data);
 73     if(this!=&other)
 74     {
 75         String tmp(other);    //再造一个String对象,将它的指针给this的m_data,m_data给它,让它在析构的时候释放掉
 76         char *p=tmp.m_data;
 77         tmp.m_data=m_data;
 78         m_data=p;
 79     }
 80     return *this;
 81 }
 82 */
 83 
 84 ostream & operator << (ostream &os, const String &ob)        /*<<输出操作符定义*/
 85 {
 86     os<<ob.m_data;
 87     return os;
 88 }
 89 
 90 int main()
 91 {
 92     String str1="abc";
 93     String str2(str1);
 94     String str3(str3);
 95     char *p = NULL;
 96     String str4(p);
 97     cout<<str1<<endl;
 98     cout<<str2<<endl;
 99     cout<<str3<<endl;
100     cout<<str4<<endl;
101     return 0;
102 }

 

posted on 2017-02-23 11:57  dengnilikai  阅读(1151)  评论(0编辑  收藏  举报