日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C++深淺拷貝和string類的兩種寫法詳解_C 語言

作者:平凡的指針 ? 更新時間: 2022-05-12 編程語言

一、深淺拷貝

拷貝這個詞對于我們來說應該不陌生,比如我們平常的復制和粘貼就是拷貝;但是如果把拷貝這個詞放到C++中來說就有一些復雜了,我們先來看一下什么是淺拷貝:

下面用字符串類來模擬實現。

class Astring
{
public:
	//構造函數
	Astring(const char* str = "")
	{
		_str = new char[strlen(str) + 1];
		strcpy(_str, str);
	}
	//采用淺拷貝寫的構造函數
	Astring(const Astring& s)
	{
		_str = s._str;
	}
	//析構函數
	~Astring()
	{
		delete[] _str;
		_str = nullptr;
	}
private:
	char* _str;
};
int main()
{
	Astring aa("hello C++");
	Astring bb(aa); //這里調用拷貝構造
	return 0;
}

當我們執行以上程序的話就會失敗,結果如下:

在這里插入圖片描述

分析如下圖所示:

在這里插入圖片描述

所以我們采用淺拷貝使用同一塊空間是不行了,那么怎么辦呢?當然是重新開一塊和別人同樣大小的空間,然后再把別人空間里面的內容給拷貝過來,而這樣就是所謂的深拷貝了;我們還是用字符串類來模擬實現深拷貝:

class Astring
{
public:
	//構造函數
	Astring(const char* str = "")
	{
		_str = new char[strlen(str) + 1];
		strcpy(_str, str);
	}
	//采用深拷貝寫的構造函數
	Astring(const Astring& s)
	{
		_str = new char[strlen(s._str) + 1];
		strcpy(_str, s._str);
	}
	//析構函數
	~Astring()
	{
		delete[] _str;
		_str = nullptr;
	}
private:
	char* _str;
};

int main()
{
	Astring aa("hello C++");
	Astring bb(aa);
	return 0;
}

分析如下圖所示:

在這里插入圖片描述

二、string類的兩種寫法

有了上面我們知道的深淺拷貝,所以我們明白類中的拷貝構造函數和賦值重載一定要用深拷貝來實現,不過拷貝構造函數和賦值重載還是有兩種寫法的。

1. 傳統寫法

傳統寫法就是要自己開辟空間自己來拷貝別人的東西,什么事情都要自己干,代碼如下:

//搞一個命名空間,里面實現自己寫的string類
namespace cjy
{
	class string
	{
	public:
		//構造函數
		string(const char* str = "")
			:_str(new char[strlen(str) + 1])
		{
			strcpy(_str, str);
		}
		//拷貝構造函數
		string(string& s)
			:_str(new char[strlen(s._str) + 1])
		{
			strcpy(_str, s._str);
		}
		//賦值重載,s1=s3
		string& operator=(const string& s)
		{
			if (this != &s)
			{
				char* tmp = new char[strlen(s._str) + 1];
				delete[] _str;
				_str = tmp;
				strcpy(_str, s._str);
			}
			return *this;
		}
		//析構函數
		~string()
		{
			delete[] _str;
			_str = nullptr;
		}
	private:
		char* _str;
	};
}

2. 現代寫法

現代寫法就是復用其它的函數,自己不用干活,交給其它函數來幫你實現,代碼如下:

//現代寫法:拷貝構造、賦值重載函數
namespace cjy
{
	class string
	{
	public:
		//構造函數
		string(const char* str = "")
		{
			_str = new char[strlen(str) + 1];
			strcpy(_str, str);
		}
		//拷貝構造函數
		string(const string& s)
			:_str(nullptr)
		{
			string tmp(s._str);
			std::swap(_str, tmp._str);
     	}
		//賦值重載
		string& operator=(string s)
		{
			std::swap(_str, s._str);
			return *this;
		}
	private:
		char* _str;
	};
}

分析如下圖所示:

在這里插入圖片描述

在這里插入圖片描述

總結

原文鏈接:https://blog.csdn.net/m0_56311933/article/details/123371239

欄目分類
最近更新