#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()
{
if (this->pAddress != NULL)
{
delete[] this->pAddress;
this->pAddress = NULL;
this->m_Capacity = 0;
this->m_Size = 0;
}
}
//拷贝函数(深拷贝)
MyArray(const MyArray& arr)
{
this->pAddress = new T[arr.m_Capacity];
this->m_Capacity = arr.m_Capacity;
this->m_Size = arr.m_Size;
for (int i = 0; i < arr.m_Size; i++)
{
this->pAddress[i] = arr[i];
}
}
//等号重载
MyArray& operator=(const MyArray &arr)
{
if (this->pAddress != NULL)
{
delete[] this->pAddress;
this->pAddress = NULL;
this->m_Capacity = 0;
this->m_Size = 0;
}
this->pAddress = new T[arr.m_Capacity];
this->m_Capacity = arr.m_Capacity;
this->m_Size = arr.m_Size;
for (int i = 0; i < arr.m_Size; i++)
{
this->pAddress[i] = arr[i];
}
return *this;
}
//重载[]获取任意值
T& operator[](const int index)
{
return this->pAddress[index];
}
//尾插法加入值
void Push_back(const T& val)
{
if (this->m_Size == this->m_Capacity)
{
return;
}
this->m_Size++;
this->pAddress[this->m_Size] = val;
}
//尾删法删除值
void Pop_back()
{
if (this->m_Size == 0)
{
return;
}
this->m_Size--;
}
int getCapacity()
{
return this->m_Capacity;
}
int getSize()
{
return this->m_Size;
}
private:
int m_Capacity;
int m_Size;
T* pAddress;
};
标签:arr,Capacity,pAddress,C++,int,MyArray,封装,模板,Size
From: https://blog.csdn.net/weixin_47768406/article/details/141387950