模板-数组的类封装(深拷贝)

浅拷贝只复制对象的基本类型,对象类型仍属于原来的引用,简而言之就是不能复制引用类型,对于一些动态创建的数据无效。深拷贝则可以

#include <iostream>
using namespace std;
#include <string>

template<class T>
class Arry
{
public:

	//有参构造 参数 容量
	Arry(int capacity) 
	{
		cout << "MyArry 有参构造调用" << endl;;
		this->m_Capacity = capacity;
		this->m_Size = 0;
		this->pAddress = new T[this->m_Capacity]; //根据容量开辟空间
	}

	//拷贝构造
	Arry(const Arry& arr)
	{
		cout << "MyArry 拷贝 调用" << endl;
		this->m_Capacity = arr.m_Capacity;
		this->m_Size = arr.m_Size;
		//    this->pAddress = arr.pAddress;   浅拷贝导致堆区重复释放
		this->pAddress=new T[arr.m_Capacity]; //深拷贝

		//将arr中的数据拷贝过来
		for (int i = 0; i < this->m_Size; i++)
		{
			this->pAddress = arr.pAddress;
		}
	}
	//operator =防止浅拷贝问题
	Arry& operator=(const Arry& arr)
	{   
		cout << "MyArry operator=调用"<<endl;
		//先判断原来堆区有无数据,如果有先释放
		if (this->pAddress != NULL)
		{
			delete[]this->pAddress;
			this->pAddress = NULL;
			this->m_Capacity = 0;
			this->m_Size = 0;
		}

		//深拷贝
		this->m_Capacity = arr.m_Capacity;
		this->m_Size = arr.m_Size;
		this->pAddress = new T[arr.m_Capacity];

		for (int i = 0; i < this->m_Size; i++)
		{
			this->pAddress[i] = arr.pAddress[i];
		}
		return *this;
	}
	//析构函数
	~Arry() {
		cout << "MyArry 析构函数调用"<<endl;
		if (this->pAddress != NULL)
		{
			delete[] this->pAddress;
			this->pAddress = NULL;
		}

	}
private :
	T* pAddress;  //指针指向堆开辟真实数组

	int m_Capacity;  //数组容量

	int m_Size;       //数组大小

};
#include "MyArry.hpp"


void test()
{
	Arry <int> arr1(5);
	Arry <int> arr2(arr1);
}

int main()
{   
	test();

	system("pause");

	return 0;
}

在这里插入图片描述


版权声明:本文为weixin_44704931原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。