C++ 基于模板类实现的自定义数组

#pragma once
#include <iostream>

using namespace std;

template<class T>
class Vector
{
public:
	Vector(int capacity)
	{
		this->m_Capacity = capacity;
		this->m_Vector  = new T[this->m_Capacity];
		this->m_Size = 0;
	}
	Vector(const Vector& v)
	{
		this->m_Capacity = v.m_Capacity;
		this->m_Size = v.m_Size;
		this->m_Vector = new T[v.m_Capacity];
		if (v.m_Size)
		{
			for (int i = 0; i < v.m_Size; ++i)
			{
				this->m_Vector[i] = v.m_Vector[i];
			}
		}
	}

	Vector& operator = (const Vector& v)
	{
		if (this->m_Vector != NULL)
		{
			delete[] this->m_Vector;
			this->m_Vector = NULL;
			this->m_Capacity = 0;
			this->m_Size = 0;
		}
		this->m_Capacity = v.m_Capacity;
		this->m_Size = v.m_Size;
		this->m_Vector = new T[v.m_Capacity];
		if (v.m_Size)
		{
			for (int i = 0; i < v.m_Size; ++i)
			{
				this->m_Vector[i] = v.m_Vector[i];
			}
		}
		return *this;
	}

	T& operator [](int n)
	{
		return this->m_Vector[n];
	}

	void Push_back(T n)
	{
		if (this->m_Size >= this->m_Capacity) 
		{
			return;
		}
		this->m_Vector[this->m_Size] = n;
		this->m_Size++;
	}

	void Pop_back()
	{
		if (this->m_Size <= 0)
		{
			return;
		}
		this->m_Size--;
	}

	int Size()
	{
		return this->m_Size;
	}

	~Vector()
	{
		if (this->m_Vector != NULL)
		{
			delete[] this->m_Vector;
			this->m_Vector = NULL;
			this->m_Capacity = 0;
			this->m_Size = 0;
		}
	}
private:
	T* m_Vector;
	int m_Capacity;
	int m_Size;
};



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值