浅拷贝(在进行其中一个对象的运算时开辟新的空间)

来源:互联网 发布:照片真假辨别软件 编辑:程序博客网 时间:2024/05/02 06:46

如图变换,且对于指向同一空间的String进行计数

代码如下:

#include <iostream>using namespace std;class String;                                             //提前声明class String_rep                                          //定义类String_rep{friend class String;                                  //友元public:String_rep(const char *str=NULL):use_count(0)         //构造{if(str == NULL){m_data = new char[1];m_data[0] = '\0';}else{m_data = new char[strlen(str)+1];strcpy(m_data,str);}}String_rep(const String_rep &r);                      //拷贝构造String_rep& operator=(const String_rep &r);           //赋值函数~String_rep(){delete []m_data;}public:void increment()                                       //计数器加一{use_count++;}void decrement()                                       //若计数器为零则释放{if(--use_count == 0){delete this;                                 }}int get_use_count()const                               //计数器{return use_count;}void Show()const                                       //显示{cout<<m_data<<endl;}private:                                                   //私有成员char *m_data;long use_count;};class String                                               //定义类String{public:String(const char *str=NULL):rep(new String_rep(str))  //构造{rep->increment();}String(const String &s):rep(s.rep)                     //拷贝构造{rep->increment();}String& operator=(const String &s)                     //赋值函数{if(this != &s)                                     //若为同一字符串{rep->decrement();rep = s.rep;rep->increment();}return *this;                                      //反之}~String()                                              //析构{rep->decrement();}public:void Show()const                                       //显示{rep->Show();}void to_upper()                                         //变为大写{String_rep *new_rep = new  String_rep(rep->m_data); //新的指针rep->decrement();                                   //原计数器减一rep = new_rep;                                      //指向新的空间rep->increment();                                   //现计数器加一char *pch = rep->m_data;                            //确定指向while(*pch != '\0')                                 //变成大写{*pch -= 32;pch++;}}private:String_rep *rep;//句柄};void main(){String s1("abcd");String s2 = s1;String s3;s3 = s2;s1.to_upper();//将s1的小写变大写s1.Show();   //ABCDs2.Show();   //abcds3.Show();   //abcd}


如果代码有不足的地方希望大家指出~谢谢。

0 0
原创粉丝点击