类模板实现—通用数组类
实现功能如下:
- 可以对内置数据类型以及自定义数据类型的数据进行存储
- 将数组中的数据存储到堆区
- 构造函数可以传入数组的容量
- 提供对应的拷贝构造函数以及operator=防止浅拷贝问题
- 提供尾插法和尾删法对数组中的数据进行增加和删除
- 可以通过下标的方式访问数组中的元素
- 可以获取数组的容量和当前元素个数
MyArray.hpp:
//自己的通用的数组类
#pragma once
#include<iostream>
using namespace std;
#include<string>
template<class T>
class MyArray {
public:
//有参构造
MyArray(int capacity) {
m_Capacity = capacity;
m_Size = 0;
pAddress = new T[m_Capacity];
}
//拷贝构造函数
MyArray(const MyArray& arr) {
this->m_Capacity = arr.m_Capacity;
this->m_Size = arr.m_Size;
//深拷贝
this->pAddress = new T[arr.m_Capacity];
//将arr中的数据拷贝过来
for (int i = 0; i < this->m_Size; i++) {
this->pAddress[i] = arr.pAddress[i];
}
}
//operator=防止浅拷贝问题
MyArray& operator=(const MyArray& arr) {
//先判断原来堆区是否有数据,如果有先释放。
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;
}
//尾插法
void Push_Back(const T &val) {
//判断容量是否已经达到上限
if (this->m_Capacity == this->m_Size) {
cout << "容量已满" << endl;
return;
}
else {
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;
}
//析构函数
~MyArray() {
if (this->pAddress != NULL) {
delete[]this->pAddress;
this->pAddress = NULL;
}
}
private:
T* pAddress;//指针指向堆区开辟的真实的数组
int m_Capacity;//数组容量
int m_Size;//数组大小
};
数组封装.cpp
#include<iostream>
using namespace std;
#include<string>
#include"MyArray.hpp"
//测试自定义数据类型
class Person {
public:
Person() {};
Person(string name, int age) {
this->m_name = name;
this->m_age = age;
}
string m_name;
int m_age;
};
void print(MyArray<Person> arr) {
for (int i = 0; i < arr.getSize(); i++) {
cout << arr[i].m_name << " " << arr[i].m_age << endl;
}
}
void test02() {
MyArray<Person> arr(10);
Person p1("a", 99);
Person p2("b", 93);
Person p3("c", 95);
Person p4("e", 97);
Person p5("f", 98);
//将数据插入到数组中
arr.Push_Back(p1);
arr.Push_Back(p2);
arr.Push_Back(p3);
arr.Push_Back(p4);
arr.Push_Back(p5);
print(arr);
cout << arr.getCapacity()<< endl;
cout << arr.getSize() << endl;
}
int main() {
test02();
system("pause");
return 0;
}