案例描述: 实现一个通用的数组类,要求如下:
-
可以对内置数据类型以及自定义数据类型的数据进行存储
-
将数组中的数据存储到堆区
-
构造函数中可以传入数组的容量
-
提供对应的拷贝构造函数以及operator=防止浅拷贝问题
-
提供尾插法和尾删法对数组中的数据进行增加和删除
-
可以通过下标的方式访问数组中的元素
-
可以获取数组中当前元素个数和数组的容量
#define _CRT_SECURE_NO_WARNINGS
#pragma once
#include <iostream>
#include <string>
using namespace std;
// 数组类的封装
template<class T>
class myArray
{
public:
// 构造函数
myArray(int capacity)
{
this->m_capacity = capacity;
this->m_size = 0;
this->p_address = new T[m_capacity];
}
// 拷贝函数
myArray(const myArray& arr)
{
this->m_capacity = arr.m_capacity;
this->m_size = arr.m_size;
// this->p_address = arr.p_address; // 浅拷贝
this->p_address = new T[m_capacity]; // 深拷贝
// 将arr中的数据都拷贝过来
for (int i = 0; i < this->m_size; i++)
{
this->p_address[i] = arr.p_address[i];
}
}
// operator= 防止浅拷贝的问题
myArray& operator= (const myArray& arr)
{
// 先置为空
if (this->p_address != NULL)
{
delete[] this->p_address;
this->p_address = NULL;
this->m_capacity = 0;
this->m_size = 0;
}
// 然后进行拷贝
this->m_capacity = arr.m_capacity;
this->m_size = arr.m_size;
this->p_address = new T[m_capacity]; // 深拷贝
// 将arr中的数据都拷贝过来
for (int i = 0; i < this->m_size; i++)
{
this->p_address[i] = arr.p_address[i];
}
return *this;
}
// 尾插法
void push_back(const T& val)
{
// 判断容量是否等于大小
if (this->m_capacity == this->m_size)
return;
// 在数组尾部插入数据
this->p_address[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->p_address[index];
}
// 返回数组容量
int get_capacity()
{
return this->m_capacity;
}
// 返回数组大小
int get_size()
{
return this->m_size;
}
// 析构函数
~myArray()
{
if (this->p_address != NULL)
{
delete [] this->p_address;
this->p_address = NULL;
this->m_capacity = 0;
this->m_size = 0;
}
}
private:
T* p_address;
int m_capacity;
int m_size;
};
测试代码
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;
#include "数组类.hpp"
void printarr(myArray<int>& arr)
{
for (int i = 0; i < arr.get_size(); i++)
{
cout << arr[i] << "\t";
}
}
int main()
{
myArray<int> arr1(5);
for (int i = 0; i < 5; i++)
{
arr1.push_back(i);
}
printarr(arr1);
cout << endl;
cout << arr1.get_capacity() << endl;
cout << arr1.get_size() << endl;
myArray<int> arr2(5);
arr2 = arr1;
arr2.pop_back();
cout << arr2.get_capacity() << endl;
cout << arr2.get_size() << endl;
return 0;
}