类模板案例-数组类封装

该博客介绍了如何使用C++编程实现一个模板类`MyArray`,它具有动态分配内存、尾部插入和删除元素、按下标访问以及获取容量和大小的功能。类中包含了构造函数、析构函数以及复制构造函数和赋值运算符重载,确保了对象正确地创建、复制和销毁。此外,还展示了如何通过指针操作堆区数据,遵循动态数组的基本操作原则。
摘要由CSDN通过智能技术生成
#pragma once
#include<iostream>
using namespace std;

template<class T>
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;i<this->Size;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;			//数组元素个数
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值