C++模板练习

MyList.hpp文件

#pragma once
#include <iostream>
#include <string>
using namespace std;
/*
*	可以对内置数据类型以及自定义数据类型的数据进行存储
*	将数组中的数据存储到堆区
*	构造函数中可以传入数组的容量
*	提供对应的拷贝构造函数以及operator = 防止浅拷贝问题
*	提供尾插法和尾删法对数组中的数据进行增加和删除
*	可以通过下标的方式访问数组中的元素
*	可以获取数组中当前元素个数和数组的容显
*/
template<class T>
class MyList
{
public:
	//构造函数有参构造
	MyList(int capacity)
	{
		cout << "有参构造调用" << endl;
		this->m_Capacity = capacity;
		this->m_Size = 0;
		this->pAddress = new T[this->m_Capacity];
	}
	//拷贝构造
	MyList(const MyList& arr)
	{
		cout << "拷贝构造调用" << endl;
		this->m_Capacity = arr.m_Capacity;
		this->m_Size = arr.m_Size;
		//深拷贝
		this->pAddress = new T[arr.m_Capacity];
		//元素复制
		for (int i = 0; i < arr.m_Size; i++)
		{
			this->pAddress[i] = arr.pAddress[i];
		}
	}
	//operator=  防止浅拷贝问题
	MyList& operator=(const MyList& arr)
	{
		cout << "operator=调用" << endl;
		//先判断原来堆区是否有数据,如果有先释放
		if (this->pAddress != NULL)
		{
			delete[] this->pAddress;
			this->pAddress = NULL;
			this->m_Capacity = 0;
			this->m_Size = 0;
		}
		this->m_Capacity = arr.m_Capacity;
		this->m_Size = arr.m_Size;
		//深拷贝
		this->pAddress = new T[arr.m_Capacity];
		//元素复制
		for (int i = 0; i < arr.m_Size; i++)
		{
			this->pAddress[i] = arr.pAddress[i];
		}
		return *this;
	}

	//析构函数
	~MyList()
	{
		cout << "析构函数调用" << endl;
		if (this->pAddress != NULL)
		{
			delete[] this->pAddress;
			this->pAddress = NULL;
		}
	}
	//尾插法
	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 getCapacity()
	{
		return this->m_Capacity;

	}
	//获取大小
	int getSize()
	{
		return this->m_Size;
	}
private:
	T *pAddress;	//指针指向堆区开辟的真实内存
	int m_Capacity;		//数组容量,最大长度
	int m_Size;		//数组的元素个数,已拥有的长度
};

测试

#pragma once
#include <iostream>
#include "mList.hpp"
using namespace std;


void printList(MyList<int> &arr)
{
	for (int i = 0; i < arr.getSize(); i++)
	{
		cout << arr[i] << endl;
	}
}

void test1()
{
	MyList<int> arr1(5);
	for (int i = 0; i < 5; i++)
	{
		arr1.Push_Back(i);
	}
	printList(arr1);
	cout << "arr1的容量:" << arr1.getCapacity() << endl;
	cout << "arr1的大小:" << arr1.getSize() << endl;
	arr1.Pop_Back();
	printList(arr1);
	cout << "arr1的容量:" << arr1.getCapacity() << endl;
	cout << "arr1的大小:" << arr1.getSize() << endl;
}

int main()
{
	test1();
	system("pause");
	return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值