实现一个通用的数组类,要求如下:
可以对内置数据类型以及自定义数据类型进行存储
将数组中的数据存储到堆区
提供对应的拷贝构造函数以及operator=防止浅拷贝问题
提供尾插法和尾删法对数组中的数据进行增加和删除
可以通过下标的方式访问数组中的元素
可以获取数组的容量和当前元素的个数
类模板代码:Array.hpp
#pragma once
#include <iostream>
using namespace std;
template<class T>
class MyArray{
public:
MyArray(int capacity){
this->m_capacity=capacity;
this->m_size=0;
this->pAddress=new T[this->m_capacity];
}
~MyArray(){
if(this->pAddress!=NULL) {
delete[] this->pAddress;
this->pAddress=NULL;
}
}
//尾插入
void Push_Back(const T &val) {
if(this->m_capacity==this->m_size) return;
this->pAddress[this->m_size++]=val;
}
//尾删除
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(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) {
this->pAddress[i]=arr.pAddress[i];
}
}
MyArray& operator = (const MyArray& arr){
this->m_capacity=arr.m_capacity;
this->m_size=arr.m_size;
if(this->pAddress!=NULL) {
delete[] this->pAddress;
this->pAddress=NULL;
}
this->pAddress=new T[this->m_capacity];
for(int i=0;i<this->m_size;++i) {
this->pAddress[i]=arr.pAddress[i];
}
return *this;
}
public:
T *pAddress;
int m_size;
int m_capacity;
};
测试代码 main.cpp
#include <iostream>
#include "Array.hpp"
using namespace std;
template<class NameType,class AgeType>
class Person{
public:
Person(){
}
Person(NameType name,AgeType age){
this->age=age;
this->name=name;
}
void show() {
cout<<age<<" "<<name<<endl;
}
NameType name;
AgeType age;
};
void test() {
MyArray<Person<string,int> >P(4);
P.Push_Back(Person<string,int>{"小明",22});
P.Push_Back(Person<string,int>{"李华",18});
P[0].show();
P[1].show();
cout<<P.getSize()<<endl;
cout<<P.getCapacity()<<endl;
}
int main()
{
test();
MyArray<int> a(100);
cout<<a.getCapacity()<<endl;
for(int i=0;i<50;i++) {
a.Push_Back(i);
}
cout<<a.getSize()<<endl;
cout<<a[45]<<endl;
a[1]=a[44]=99;
cout<<a[1]<<endl;
a.Pop_Back();
cout<<a.getSize()<<endl;
return 0;
}