zoukankan      html  css  js  c++  java
  • 使用单例模式实习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 }
  • 相关阅读:
    【Silverlight】汉诺塔游戏,带AI
    Farseer Physics Engine
    解决SilverLight的图片裁剪问题
    【C#】三维立体验证码 (3DCaptcha)
    又一个“众所周知”的DAL层设计BUG
    【C#】性别类
    36进制条码序列号生成器 [更新]
    理想的软件设计标准
    表驱动法概念到实战(一) 原理及基本运用
    Sudoku solver
  • 原文地址:https://www.cnblogs.com/newworldcom/p/4972101.html
Copyright © 2011-2022 走看看