实现一个通用的数组类

要求:

  • 可以对内置数据类型以及自定义的数据类型的数据进行存储
  • 将数组中的数据存储到堆区
  • 构造函数可以传入数组的容量
  • 提供对应的拷贝构造函数和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;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值