国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

String類的寫時拷貝實例

2020-05-23 13:53:51
字體:
來源:轉載
供稿:網友

實例如下:

#include<iostream>using namespace std; class String;ostream& operator<<(ostream &out, const String&s);//引用計數器類class String_rep {  friend class String;  friend ostream& operator<<(ostream &out, const String&s);public:    String_rep(const char *str )      :use_count(0)    {      if (str == NULL)      {        data = new char[1];        data[0] = '/0';      }      else      {        data = new char[strlen(str) + 1];        strcpy(data, str);      }    }      String_rep(const String_rep &rep) :use_count(0)    {      data = new char[strlen(rep.data) + 1];      strcpy(data, rep.data);    }    String_rep& operator=(const String_rep &rep)    {      if (this != &rep)      {        delete[]data;        data = new char[strlen(rep.data) + 1];        strcpy(data, rep.data);      }      return *this;    }    ~String_rep()    {        delete[]data;        data = NULL;    }public:  void increase()  {    ++use_count;  }    void decrease()  {    if (use_count == 0)    {      delete this; //自殺行為  釋放this所指的空間,在釋放之前調動這個類的析構函數     }  }private:    char *data;    int use_count;};////////////////////////////////////////////////////////////////////////////////////////class String{   friend ostream& operator<<(ostream &out, const String&s);public:  String(const char* str = " ")  {    rep = new String_rep(str);    rep->increase();  }  String(const String &s)  {    rep = s.rep;   //淺拷貝    rep->increase();  }  String& operator=(const String &s)  {    if (this != &s)    {      rep->decrease();  //模擬delete      rep = s.rep;      //模擬new      rep->increase();   //模擬strcpy      /*rep = s.rep;  //這會更改引用計數器指針 ,造成s內存泄漏      rep->increase();*/    }    return *this;  }    ~String()    {      rep->decrease();    }public:  void to_upper()  {    if (rep->use_count > 1)    {      String_rep* new_rep = new String_rep(rep->data);      rep->decrease();      rep = new_rep;      rep->increase();    }    char* ch = rep->data;    while (*ch != '/0')    {      *ch -= 32;      ++ch;    }  }private:  String_rep *rep; //引用計數器};ostream& operator<<(ostream &out, const String&s){  out << s.rep->data;  return out;}void main(){  String s1("hello");  String s2(s1);  String s3;  s3 = s2;  cout << "s1=" << s1 << endl;  cout << "s2=" << s2 << endl;  cout << "s3=" << s3 << endl;   s2.to_upper();  cout << "-----------------------------------------------" << endl;    cout << "s1=" << s1 << endl;  cout << "s2=" << s2 << endl;  cout << "s3=" << s3 << endl;}

以上這篇String類的寫時拷貝實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 建瓯市| 江西省| 九龙城区| 渑池县| 宿松县| 阜康市| 东阳市| 凌源市| 阿瓦提县| 凤凰县| 磐安县| 景东| 庆阳市| 陆河县| 平昌县| 婺源县| 永仁县| 名山县| 枞阳县| 开原市| 旬邑县| 厦门市| 清远市| 龙川县| 泗水县| 阳信县| 襄汾县| 云林县| 日喀则市| 罗山县| 图片| 长治市| 黔江区| 仁寿县| 凤庆县| 祁连县| 双牌县| 依兰县| 香河县| 鄂托克旗| 新沂市|