C++ string数据类型的实现

 1 #include <cstdlib>
 2 #include <cstring>
 3 
 4 class Mystring
 5 {
 6 public:
 7     Mystring(const char * pdata)
 8     {
 9         if(pdata==NULL)
10         {
11             data = new char[1];
12             *data = '\0';
13         }
14         else
15         {
16             int len = strlen(pdata);
17             data = new char[len+1];
18             strcpy(data,pdata);
19         }
20     }
21     Mystring(const Mystring &str)
22     {
23         int len = strlen(str.data);
24         data = new char[len+1];
25         strcpy(data,str.data);
26     }
27 
28     Mystring &operator=(const Mystring &str)
29     {
30         if(this!=&str)
31         {
32             Mystring strTemp(str);
33             char *pTemp = strTemp.data;
34             strTemp.data = this->data;
35             this->data = pTemp;
36         }
37         return this;
38     }
39     ostream & operator<<(ostream &os,const Mystring &str)
40     {
41         os<<str.data;
42         return os;
43     }
44     Mystring & operator+(const Mystring & str)const
45     {
46         if(str.data!=NULL)
47         {
48             int len1 = strlen(str.data);
49             int len2 = strlen(this->data);
50             Mystring strTemp(*(this->data));//创建一个临时对象保存原来对象的数据
51             delete []data;//删除原来的数据
52             data=NULL;
53             data = new char[len1+len2+2];//开闭新的空间
54             strcpy(data,strTemp.data);//复制
55             strcat(data,str.data);//拼接
56         }
57         return this;
58     }
59 
60     char & operator[](int index)//char返回引用,是为了我们之后可以修改字符串
61     {
62         int len = strlen(data);
63         if(index>len||index<0)
64         {
65             perror("index is not in the cope!");
66             exit(0);
67         }else
68             return *((this->data)+index);
69     }
70 
71     ~Mystring()
72     {
73         delete []data;
74     }
75 private:
76     char * data;
77 };

 

posted @ 2015-10-27 11:02  HOU_JUN  阅读(637)  评论(0编辑  收藏  举报