STL:模板类手写数组

#include <iostream>
using namespace std;

template<class T>
class MyArray {
	friend void test01();//友元函数
public:
	MyArray(int capacity)//构造函数
	{
		this->mCapacity = capacity;
		this->mSize = 0;
		//申请空间
		this->ptr = new T[this->mCapacity];

	}
	MyArray(const MyArray<T>& another)//拷贝函数
	{
		this->mCapacity = another.mCapacity;
		this->mSize = another.mSize;
		//申请空间
		this->ptr = new T[this->mCapacity];
		//开始拷贝
		for (int i = 0; i < this->mSize; i++)
		{
			this->ptr[i] = another.ptr[i];
		}
	}
	T& operator[](int index)// []操作符重载
	{
		return this->ptr[index];
	}
	MyArray<T>& operator=(const MyArray<T>& another)// =操作符重载
	{
		//原本容器有值
		if (this->ptr != nullptr) {
			delete[] this->ptr;
			this->ptr = nullptr;
			this->mCapacity = 0;
			this->mSize = 0;
		}
		this->mCapacity = another.mCapacity;
		this->mSize = another.mSize;
		this->ptr = new T[this->mCapacity];
		for (int i = 0; i < this->mSize; i++)
		{
			this->ptr[i] = another.ptr[i];
		}
		return *this;
	}
	void PushBack(T& data) {//一个&是对左值取引用
		//判断容器中是否有位置
		if (this->mCapacity <= this->mSize) {
			return ;
		}
		this->ptr[this->mSize] = data;
		this->mSize++;
	}

	void PushBack(T&& data) {//两个&&是对右值取引用
		//判断容器中是否有位置
		if (this->mCapacity <= this->mSize) {
			return ;
		}
		this->ptr[this->mSize] = data;
		this->mSize++;
}
	~MyArray() {
		if (this->ptr != nullptr) {
			delete[] this->ptr;
			this->ptr = nullptr;
			this->mCapacity = 0;
			this->mSize = 0;
		}
	}
private:
	//一共可以存储多少元素
	int mCapacity;
	//现在有多少元素
	int mSize;
	//保存数据的首地址
	T* ptr;
};
void test01() {
	//测试构造函数
	MyArray<int> marray(20);
	int a = 10, b = 20, c = 30;
	//测试数组内添加元素
	//对左值取引用
	marray.PushBack(a);
	marray.PushBack(b);
	marray.PushBack(c);
	//对右值取引用
	marray.PushBack(1);
	marray.PushBack(2);
	marray.PushBack(3);
	//测试[ ]操作符重载
	for (int i = 0; i < marray.mSize; i++) {
		cout << marray[i] << " ";
	}
}

int main() {
	test01();
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值