使用单例模式实习string类

  1 class  mystring
  2 {
  3 private:
  4     char *s;
  5     static mystring *self;
  6 public:
  7     ~ mystring();
  8     const char *get_s() const;
  9     const void set_s(const char *s);
 10      static mystring *makestring(const char *s = NULL);
 11      static void deletestring();
 12 protected:
 13      mystring();
 14     mystring(const mystring &it);  //构造函数
 15     mystring(const char *s);
 16 
 17 };
 18 
 19 mystring *mystring::self = NULL;
 20 
 21 mystring::mystring():s(NULL)
 22 {
 23 
 24 }
 25 
 26 mystring::mystring(const char *s)
 27 {
 28     int len = strlen(s);
 29     this->s = new char[len +1];
 30     strcpy(this->s,s);
 31     this->s[len] = 0;
 32 }
 33 
 34 
 35 mystring::mystring(const mystring &it) //通过拷贝构造函数实现深拷贝
 36 {
 37     int len = strlen(it.get_s());
 38     this->s = new char[len +1];
 39     strcpy(this->s, it.s);
 40     this->s[len] = 0;
 41 }
 42 
 43 mystring::~mystring()
 44 {
 45     delete s;
 46     s = NULL;
 47 }
 48 
 49 const char *mystring::get_s() const
 50 {
 51     return s;
 52 }
 53 
 54 const void mystring::set_s(const char *s)
 55 {
 56     if(this->s == NULL)
 57     {
 58         int len = strlen(s);
 59         this->s = new char[len +1];
 60         strcpy(this->s, s);
 61         this->s[len] = 0;
 62     }
 63     else
 64     {
 65         int len1 = strlen(this->s);
 66         int len2 = strlen(s);
 67         if(len1 >= len2)
 68         {
 69             strcpy(this->s, s);
 70             this->s[len2] = 0;
 71         }
 72         else
 73         {
 74             delete []this->s;
 75             this->s = new char[len2+1];
 76             strcpy(this->s, s);
 77             this->s[len2] = 0;
 78         }
 79     }
 80 }
 81 
 82 mystring *mystring::makestring(const char *s)
 83 {
 84     if(self == NULL)
 85     {
 86         if(s == NULL)
 87         {
 88             self = new mystring;
 89         }
 90         else
 91         {
 92             self = new mystring(s);
 93         }
 94     }
 95     return self;
 96 }
 97 
 98 void mystring::deletestring()
 99 {
100     if(self != NULL)
101     {
102         delete self;
103         self = NULL;
104     }
105     
106 }

 

转载于:https://www.cnblogs.com/newworldcom/p/4972101.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值