类模板案例
案例描述: 实现一个通用的数组类,要求如下:
- 可以对内置数据类型以及自定义数据类型的数据进行存储
- 将数组中的数据存储到堆区
- 构造函数中可以传入数组的容量
- 提供对应的拷贝构造函数以及operator=防止浅拷贝问题
- 提供尾插法和尾删法对数组中的数据进行增加和删除
- 可以通过下标的方式访问数组中的元素
- 可以获取数组中当前元素个数和数组的容量
- 后续会新增功能。。。
```cpp
#pragma once
#include<iostream>
#include<string>
using namespace std;
template<class T>
class MyArray
{
public:
MyArray() {}; //默认构造函数
MyArray(int capacity) //有参构造函数,构造传入大小的数组
{
this->m_Capacity = capacity;
this->m_size = 0;
this->pAddress = new T[capacity];
}
MyArray(const MyArray& arr)
{
this->m_Capacity = arr.m_Capacity;
this->m_size = arr.m_size;
this->pAddress = new T[this->m_Capacity]; //深拷贝重新在堆区申请资源
for (int i = 0; i < this->m_size; ++i) //将实参arr数组中的内容拷贝到新建立的对象中
{
this->pAddress[i] = arr.pAddress[i];
}
}
// 重载运算符“=”,有时候会出现对象之间的赋值操作,此时就要用到“=”
MyArray& operator=(const MyArray& arr)
{
/*首先要将左侧的对象置空,然后进行拷贝操作*/
if (this->pAddress != NULL)
{
delete[] this->pAddress; //delete删除数组的时候中间要加上中括号
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[this->m_Capacity];
for (int i = 0; i < this->m_size; ++i)
{
this->pAddress[i] = arr.pAddress[i];
}
}
/*尾插法的实现*/
bool push_back(const T& val)
{
//判断数组是否满了,满了的话就打印插入错误信息并退出函数
if (this->m_size == this->m_Capacity)
{
cout << "求求你别再插了,都满啦!!!!!!!!" << endl;
return false;
}
else
{
this->pAddress[this->m_size] = val; //在数组末尾插上添加的数据
++this->m_size; //将数组大小进行加一操作
return 0;
}
}
/*尾删法的实现*/
bool pop_back()
{
//判断数组是否为空,为空就不能进行删除操作,此时打印错误输出
if (this->m_size == 0)
{
cout << "求求你别删了,我真的一个都没有了" << endl;
return false;
}
else
{
//逻辑删除,只需将数组的大小进行减一操作即可
--this->m_size;
return true;
}
}
//当我们的希望可以通过 T[i]这样的方式访问到T数组中的参数时
//一般做法是通过构造get_pAddress函数获取数组中的内容
//但是我们可以使用运算符重载,重载[]运算符就能很方便的访问到我们的元素内容了
T& operator[](int index)
{
//在这里我们可以判断下用户输入的索引数字是否合理
if (index < 0 || index >= this->m_size)
cout << "你在瞎填啥呢, 年轻人不讲武德!!!!!" << endl;
else
return this->pAddress[index];
}
//返回数组大小
int getSize()
{
return this->m_size;
}
//返回容量大小
int getCapacity()
{
return this->m_Capacity;
}
//看 由于下面的成员变量是不是有指针类型啊,是不是会在堆区开辟数据啊
//都看到了还不写析构函数,你想干啥呢
~MyArray()
{
//判断有没有在堆区开辟数据
if (this->pAddress != NULL)
{
delete[] this->pAddress;
this->pAddress = NULL;
}
}
private:
T* pAddress = NULL;
int m_Capacity;
int m_size;
};
总结:基本实现了自定义数组类型的实现,最重要的是使用了模板进行编程,这是我第一次使用模板写代码,后续会在上面新增功能模块,比如当数组存满了可以自动的扩大空间,打造成类似于一个vector容器的样子,虽然我还没去看vector的源码,但是应该不难实现,从这个案例中我们也能看到vector这种操作方式应该也是由模板实现的