1. 程式人生 > >淺拷貝(在進行當中一個對象的運算時開辟新的空間)

淺拷貝(在進行當中一個對象的運算時開辟新的空間)

int 構造 nts iostream alt 小寫 釋放 fcm pri

技術分享

如圖變換,且對於指向同一空間的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();   //ABCD
	s2.Show();   //abcd
	s3.Show();   //abcd
}


假設代碼有不足的地方希望大家指出~謝謝。

淺拷貝(在進行當中一個對象的運算時開辟新的空間)