栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

类模板案例-数组类封装

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

类模板案例-数组类封装

#pragma once
#include
using namespace std;

template
class MyArray {
public:
	MyArray(int Capacity) {
		this->Capacity = Capacity;
		this->Size = 0;
		this->pAddress = new T[this->Capacity];

	}

	//尾插法
	void PushBack(const T& val) {
		//判断容量是否等于大小
		if (this->Capacity == this->Size)
			return;
		this->pAddress[this->Size] = val;
		this->Size++;
	}

	//尾删法
	void PopBack() {
		//让用户访问不到最后一个元素即可。逻辑删除
		if (this->Size == 0)
			return;
		this->Size--;
	}

	//通过下标方式访问数组中的元素
	T& operator[](int index) {
		return this->pAddress[index];
	}

	//返回数组的容量
	int getCapacity() {
		return this->Capacity;
	}

	//返回数组的数据元素个数
	int getSize() {
		return this->Size;
	}

	~MyArray() {
		if (this->pAddress != NULL) {
			delete[] this->pAddress;
			this->pAddress = NULL;
			this->Capacity = 0;
			this->Size = 0;
		}
	}

	MyArray(const MyArray& arr) {
		this->Capacity = arr.Capacity;
		this->Size = arr.Size;
		this->pAddress = new T[arr.Capacity];
		for(int i=0;iSize;i++)
			this->pAddress[i] = arr.pAddress[i];
	}

	MyArray& operator=(const MyArray& arr) {
		//先判断原来堆区是否有数据,如果有,先释放
		if (this->pAddress != NULL) {
			delete[]this->pAddress;
			this->pAddress = NULL;
			this->Capacity = 0;
			this->Size = 0;
		}
		this->Capacity = arr.Capacity;
		this->Size = arr.Size;
		this->pAddress = new T[arr->Capacity];
		for (int i = 0; i < this->Size; i++)
			this->pAddress[i] = arr.pAddress[i];

		return *this;
	}
private:
	T* pAddress;		//指针指向堆区开辟的真实数组

	int Capacity;       //数组容量

	int Size;			//数组元素个数
};

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/330199.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号