String 类的传统实现法,客官有兴趣吗

string类是我们日常引用较多的一个类,这个类有不少人模拟实现过,下面我也来模拟实现一把

  1 #include <iostream>
  2 #include <string.h>
  3 using namespace   std;
  4 class String
  5 {
  6         public:
  7                 String ()
  8                         :_str(new  char[1])
  9                 {
 10                         _str[0]='\0';
 11                 }
 12                 String (char*str)
 13                         :_str(new char [strlen (str)+1])
 14                 {
 15                         strcpy (_str,str);
 16                 }
 17 
 18 
 19 
 20 
 21                 String (const String&  s)
 22                 {
 23                         this ->_str=new char [strlen (s._str+1)];
 24                         strcpy(_str,s._str);
 25                 }
 26 
 27 
 28 
 29                 String&  operator= (const String&  s)
 30                 {
 31                         if (this !=&s)
 32                         {
 33                                 delete[]  _str;
 34                                 _str =new char [strlen (s._str)+1];
 35                                 strcpy (_str,s._str);
 36                         }
 37                         return *this ;
 38                 }
 39 
 40 
 41 
 42                 ~String ()
 43                 {
 44                         if (_str)
 45                         {
 46                                 delete[]_str;
 47                                 _str=NULL;
 48                         }
 49                 }
 50 
 51 
 52 
 53 
 54 
 55                 const char *c_str()
 56                 {
 57                         return _str;
 58                 }
 59 
 60 
 61 
 62         private:
 63                 char* _str;
 64 };

这就是String的传统写法,如果认真观察我们会发现其实构造原理呢都是为类对象中的字符串开辟空间,然后向开辟的空间中写入要写入的字符串。讲到这里有人问了那既然有传统写法应该就有现代写法啊,那现代写法https://blog.csdn.net/a15929748502/article/details/81507476是什么样的呢,别急啊,且听我慢慢道来

猜你喜欢

转载自blog.csdn.net/a15929748502/article/details/81505333