到这里,模板相关基本学习完,现在来利用模板类写一个代码例子。这个例子就是自定义一个数组模板类,需要实现数组的一些常用操作。例如拷贝,有参构造,查找,删除等。
1.自定义数组类需求
模板案例描述:实现一个通用的数组类,要求如下
1)可以对内置数据类型以及自定义数据类型的数据进行存储
2)将数组中的数据存储到堆区
3)构造函数中可以传入数组的容量
4)提供对应得拷贝构造函数以及operator=防止浅拷贝问题
5)提供尾插法和尾删法对数组中的数据进行增加和删除
6)可以通过下标的方式访问数组中的元素
7)可以获取数组中当前元素个数和数组的容量
2.实现有参构造,拷贝构造,operater=重载 和析构函数
一个数组,里面有这么几个属性,数组容量,数组元素个数,数组本身内存地址,这几个数据都是定义私有类型,提供有参构造,让用户可以构造出这个数组对象。下面是有参构造和拷贝构造和析构函数还有operator=重载的代码
在前面类模板中成员函数创建有这个主意问题,最好的办法就是把类模板写在一个hpp的文件中,不要拆开写成多个文件。
myArray.hpp代码如下
#include <iostream>
#include <string>
using namespace std;
template <class T>
class myArray{
public:
// 有参构造函数
myArray(int capacity)
{
cout << "myArray 的有参构造被调用" << endl;
this->m_Capacity = capacity;
this->m_Size = 0;
this->pAddress = new T[this->m_Capacity];
}
// 拷贝构造
myArray(const myArray& arr)
{
cout << "myArray 的有拷贝造被调用" << endl;
this->m_Capacity = arr.m_Capacity;
this->m_Size = arr.m_Size;
//this-pAddress = arr.pAddress; // 指针不能这样浅拷贝赋值,会出现堆区数据重复释放
// 这里需要做深拷贝
this->pAddress = new T[arr.m_Capacity];
// 如果数组中还有元素也需要拷贝过来
for(int i=0; i < this->m_Size; i++)
{
this->pAddress[i] = arr.pAddress[i];
}
}
// operate= 重载函数
myArray& operator=(const myArray& arr)
{
cout << "myArray 的有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 < this->m_Size; i++)
{
this->pAddress[i] = arr.pAddress[i];
}
return *this;
}
//析构函数
~myArray()
{
if(this->pAddress != NULL)
{
cout << "myArray 的析构被调用" << endl;
delete [] this->pAddress; // 清空内存
this->pAddress = NULL; // 指针置空,防止野指针
}
}
private:
T * pAddress; // 指针,维护是指向堆区中真实开辟出来数组
int m_Capacity; // 数组的容量
int m_Size; // 数组大小(元素个数)
};
3.测试有参构造和析构函数
来写一个测试代码,测试我们的有参构造和析构是否被正常调用
#include <iostream>
#include <string>
#include "myArray.hpp"
using namespace std;
void test01()
{
myArray <int>arr(5);
}
int main()
{
test01();
system("pause");
return 0;
}
运行
接下来,测试下拷贝构造和operator=函数
#include <iostream>
#include <string>
#include "myArray.hpp"
using namespace std;
void test01()
{
myArray <int>arr1(5); //有参构造
myArray <int>arr2(arr1); //拷贝构造
}
int main()
{
test01();
system("pause");
return 0;
}
运行看看是否显示拷贝构造调用
还有一个operator=的函数重载测试
#include <iostream>
#include <string>
#include "myArray.hpp"
using namespace std;
void test01()
{
myArray <int>arr1(5); //有参构造
myArray <int>arr2(arr1); //拷贝构造
myArray <int>arr3(100);
arr1 = arr3; // =号赋值
}
int main()
{
test01();
system("pause");
return 0;
}
下一篇继续实现数组的其他功能,这篇已经实现并测试数组有参构造和拷贝构造和=号赋值的函数以及析构函数。但是创建的数据没有元素,元素相关操作在下一篇学习代码实现和代码测试。