實(shí)例如下:
成都創(chuàng)新互聯(lián)公司專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于網(wǎng)站設(shè)計制作、成都做網(wǎng)站、延平網(wǎng)絡(luò)推廣、重慶小程序開發(fā)公司、延平網(wǎng)絡(luò)營銷、延平企業(yè)策劃、延平品牌公關(guān)、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運(yùn)營等,從售前售中售后,我們都將竭誠為您服務(wù),您的肯定,是我們最大的嘉獎;成都創(chuàng)新互聯(lián)公司為所有大學(xué)生創(chuàng)業(yè)者提供延平建站搭建服務(wù),24小時服務(wù)熱線:13518219792,官方網(wǎng)址:www.cdcxhl.com
#includeusing namespace std; class String; ostream& operator<<(ostream &out, const String&s); //引用計數(shù)器類 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所指的空間,在釋放之前調(diào)動這個類的析構(gòu)函數(shù) } } 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; //這會更改引用計數(shù)器指針 ,造成s內(nèi)存泄漏 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; //引用計數(shù)器 }; 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類的寫時拷貝實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持創(chuàng)新互聯(lián)。