C++研发 泛型编程 第二讲 【自定义类型数组】

简介

这是一个模板类,具有增加和删除功能,并可以通过数组下标访问元素。而数组的类型可以是如int,char等内置数据类型,也可以是自定义数据类型,如Person类等。

下面开始一一讲解:

成员变量:

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

	int m_Capacity;//数组容量

	int m_Size;//数组最大元素下标,也就是数组目前大小

有参构造函数:

public:
	MyArray(int capacity)
	{
		this->m_Capacity = capacity;
		this->m_Size = 0;
		this->pAddress = new T[this->m_Capacity];
	}

拷贝构造函数:

//拷贝构造
	MyArray(const MyArray& arr)
	{
		this->m_Capacity = arr.m_Capacity;
		this->m_Size = arr.m_Size;
		//深拷贝
		this->pAddress = new T[arr.m_Capacity];
		//将arr中的数据都拷贝过来
		for (int i = 0; i < this->m_Size; i++)
		{
			this->pAddress[i] = arr.pAddress[i];
		}
		//operator= 防止浅拷贝问题
	}

等号重载:

MyArray& operator=(const MyArray& arr)
	{
		//先判断原来堆区是否有数据,如果有,先释放
		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];
		//将arr中的数据都拷贝过来
		for (int i = 0; i < this->m_Size; i++)
		{
			this->pAddress[i] = arr.pAddress[i];
		}
		return *this;
	}

尾插法:

//尾插法
	void Push_Back(const T& val)
	{
		if (this->m_Capacity == this->m_Size)
		{
			cout << "已经放满!" << endl;
			return;
		}
		this->pAddress[this->m_Size] = val;
		this->m_Size++;//更新数组大小
	}

尾删法:


	//尾删法
	void Pop_Back(const T& val)
	{
		//让用户访问不到最后一个元素,即为尾删,逻辑删除
		if (this->m_Size == 0)
		{
			cout << "没有可以删除的元素!" << endl;
			return;
		}
		this->m_Size--;
	}

通过下标访问元素:

//通过下标访问元素
	T& operator[](int index)
	{
		return this->pAddress[index];
	}

返回数组容量:

//返回数组容量
	int getCapacity()
	{
		return this->m_Capacity;
	}

返回数组大小:

//返回数组大小
	int getSize()
	{
		return this->m_Size;
	}

析构函数:

//析构函数
	~MyArray()
	{
		if (this->pAddress != NULL)
		{
			delete[] this->pAddress;
			this->pAddress = NULL;
		}
	}

测试代码:

1、int类型

void printIntArray(MyArray<int>& arr)
{
	for (int i = 0; i < arr.getSize(); i++)
	{
		cout << arr[i] << endl;
	}
}

void test01()
{
	MyArray<int>arr1(5);

	for (int i = 0; i < 5; i++)
	{
		arr1.Push_Back(i);
	}
	arr1.Pop_Back(4);
	cout << "arr1的打印输出为:"<< endl;
	printIntArray(arr1);
}

运行结果:

2、自定义类型

void printPersonArray(MyArray<Person>& arr)
{
	for (int i = 0; i < arr.getSize(); i++)
	{
		cout << "姓名:" << arr[i].m_Age << endl;
		cout << "年龄:" << arr[i].m_Name << endl;
	}
}

void test02()
{
	MyArray<Person> arr(10);
	Person p1("kk", 99);
	Person p2("aa", 21);
	Person p3("ww", 22);
	Person p4("ee", 23);

	arr.Push_Back(p1);
	arr.Push_Back(p2);
	arr.Push_Back(p3);
	arr.Push_Back(p4);

	printPersonArray(arr);
}

运行结果:

GitHub地址:https://github.com/kukeoo/C-_Learning.git

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值