要求:
- 可以对内置数据类型以及自定义的数据类型的数据进行存储
- 将数组中的数据存储到堆区
- 构造函数可以传入数组的容量
- 提供对应的拷贝构造函数和operator=以防止浅拷贝问题
- 提供尾插法和尾删法对数组的数据进行增加和删除
- 可以通过下标的方式访问数组中的元素
- 可以获得数组中当前元素个数和数组容量
#pragma once
#include<iostream>
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& myArray)
{
this->m_Capacity = myArray.m_Capacity;
this->m_Size = myArray.m_Size;
//this->pAddress = myArray.pAddress;
this->pAddress=new T[myArray.Capacity];
for (int i = 0; i < this->m_Size; i++)
{
this->pAddress[i] = myArray.pAddress[i];
}
}
MyArray& operator=(const MyArray& myArray)
{
if (this->m_Capacity != nullptr)
{
delete[]this->pAddress;
this->pAddress = nullptr;
this->m_Capacity = 0;
this->m_Size = 0;
}
this->m_Capacity = myArray.m_Capacity;
this->m_Size = myArray.m_Size;
this->pAddress = new T[myArray.Capacity];
for (int i = 0; i < this->m_Size; i++)
{
this->pAddress[i] = myArray.pAddress[i];
}
return *this;
}
void push_Back(const T& val)
{
if (this->m_Capacity == this->m_Size)
{
return;
}
this->pAddress[this->m_Size] = val;
this->m_Size++;
}
void pop_Back()
{
if (this->m_Size == 0)
{
return;
}
this->m_Size--;
}
T& operator[](int index)
{
return this->pAddress[index];
}
int get_Capacity()
{
return this->m_Capacity;
}
int get_Size()
{
return this->m_Size;
}
~MyArray()
{
if (this->pAddress != nullptr)
{
delete[]this->pAddress;
this->pAddress = nullptr;
}
}
T* pAddress;
int m_Capacity;
int m_Size;
};