案例描述:实现一个通用的数组类,要求如下:
- 可以对内置数据类型以及自定义数据类型的数据进行存储
- 将数组中的数据存储到堆区
- 构造函数中可以传入数组容量
- 提供对应的拷贝构造函数以及
operator=
防止浅拷贝问题 - 提供尾插法和尾删法堆数组中数据进行添加和删除
- 可以通过下标方式访问数组中元素
- 可以获取数组中当前元素个数和数组的容量
.hpp文件
#include <iostream>
#include <string>
using namespace std;
template<class T>
class MyArray
{
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 = arr.pAddress;
//深拷贝
this->pAddress = new T[arr->m_Capacity];
//拷贝数据
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];
//拷贝数据
for(int i = 0; i < this->m_Size; i++)
{
this->pAddress[i] = arr.pAddress[i];
}