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

如图变换,且对于指向同一空间的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] = '';
		}
		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 != '')                                 //变成大写
		{
			*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();   //ABCD
	s2.Show();   //abcd
	s3.Show();   //abcd
}


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

原文地址:https://www.cnblogs.com/yxysuanfa/p/6837771.html