使用类模板封装数组类
案例描述:实现一个通用的数组类
- 可以对内置的数据类型以及自定义数据类型的数据进行存储
- 将数组中的数据存储到堆区
- 构造函数中可以传入数组的容量
- 提供对应的拷贝函数以及operator=防止浅拷贝问题
- 提供尾插法和尾删法对数组中的数据进行增加和删除
- 可以通过下标的方式访问数组中的元素
- 可以获取数组当中当前元素个数和数组的容量
TList.hpp
#pragma once
#pragma once
#include <iostream>
#include <string>
using namespace std;
template<class T>
class TList
{
private:
//数组记录信息
T* array;
//自定义数组的容量
int* m_Capactity;
//当前数组已有的数据数量
int* m_Size;
public:
//构造函数,可以传递数组的容量信息
TList(int capactity)
{
if (this->array != NULL)
{
//释放原本的信息
delete[] this->array;
this->array = NULL;
}
//在堆区创建一个可以放置目标容量数据的内存区块
this->array = new T[capactity];
//已放置的数据索引设置为0
this->m_Size = new int(0);
//初始化容量信息
this->m_Capactity = new int(capactity);
}
//拷贝构造函数
TList(const TList& list)
{
this->array = new T[*list.m_Capactity];
//值拷贝
for (int i = 0; i < *list.m_Size; i++)
{
this->array[i] = list.array[i];
}
this->m_Capactity = new int(*list.m_Capactity);
this->m_Size = new int(*list.m_Size);
}
//operator = 防止浅拷贝问题
TList& operator=(const TList& list)
{
if (this->array != NULL)
{
delete[] this->array;
this->array = NULL;
this->m_Capactity = 0;
this->m_Size = 0;
}
//深拷贝
this->array = new T[*list.m_Capactity];
//值拷贝
for (int i = 0; i < *list.m_Size; i++)
{
this->array[i] = list.array[i];
}
this->m_Capactity = new int(*list.m_Capactity);
this->m_Size = new int(*list.m_Size);
}
//重载[]下标访问模式
T& operator[](int index)
{
return this->array[index];
}
//析构函数
~TList()
{
if (this->array != NULL)
{
//释放原本的信息
delete[] this->array;
this->array = NULL;
}
if (this->m_Size != NULL)
{
//释放原本的信息
delete this->m_Size;
this->m_Size = NULL;
}
if (this->m_Capactity != NULL)
{
//释放原本的信息
delete this->m_Capactity;
this->m_Capactity = NULL;
}
}
//尾插法
void add(const T& t)
{
this->array[*this->m_Size] = t;
int size = (*this->m_Size) + 1;
if (this->m_Size != NULL)
{
//释放原本的信息
delete this->m_Size;
this->m_Size = NULL;
}
this->m_Size = new int(size);
}
//尾删法
void remove()
{
if (this->m_Size == 0)
{
return;
}
this->m_Size--;
}
//获取数组的容量
int getCapactit()
{
return *this->m_Capactity;
}
//获取数组的容量
int size()
{
return *this->m_Size;
}
};
调用案例:
main.cpp
#include <iostream>
#include <string>
#include "TList.hpp"
int main()
{
TList<string> list_1(100);
TList<string> list_2(list_1);
list_1.add("string");
std::cout << " list_1[0] = " << list_1[0] << std::endl;
std::cout << "size = " << list_1.size() << std::endl;
}
运行结果:
上述案例还可以进行扩展,包括但不限于删除某下标,数组排序等相关功能。