模板头文件 .hpp
#pragma once
#include<iostream>
#include<string>
using namespace std;
template<class T>
class Myarray
{
public:
explicit Myarray(int spacedate)//explicit 防止隐式类型转换 myarray arr =10;
{
this->max =spacedate;
this->Parray = new T[this->max];
this->size =0;
}
Myarray(const Myarray& art)
{
this->Parray= new T[art->max];
this->size = art.size;
this->max = art.max;
for (int i = 0; i < size; i++)
{
this->Parray[i] = art.Parray[i];
}
}
~Myarray()
{
if(this->Parray != NULL)
{
delete[] this->Parray;
this->Parray = NULL;
}
}
Myarray& operator=(Myarray& p2)//p1=p2
{
f(this->Parray != NULL)
{
delete[] this->Parray;
this->Parray = NULL;
}
this->Parray= new T[art->max];
this->size = art.size;
this->max = art.max;
for (int i = 0; i < size; i++)
this->Parray[i] = art.Parray[i];
}
//[]重载
T& operator[](int index)
{
return this->Parray[index];
}
//插入,尾插法
void push_back(T val)
{
this->Parray[this->size]=val;
this->size++;
}
//获取数组大小
int getsize()
{
return this->size;
}
//获取容量
int getmax()
{
return this->max;
}
private:
T * Parray;
int max;//容量
int size;//当前大小
};
使用头文件对封装后的数组进行操作
#include"ArrayPackage.hpp"
void arrayprint(Myarray<int>& p)
{
for (int i = 0; i < p.getsize(); i++)
{
cout<<p[i]<<" ";
}
cout<<endl;
}
class person
{
public:
person(){}
person(string name,int age):tname(name),tage(age){}
string tname;
int tage;
};
void arrayprint(Myarray<person>& p)
{
for (int i = 0; i < p.getsize(); i++)
{
cout<<p[i].tname<<" "<<p[i].tage<<" ";
}
cout<<endl;
}
void test()
{
Myarray<int>arr(10);
for(int i=0;i<10;i++)
{
arr.push_back(i+10);
}
arrayprint(arr);
person p1("a",10);
person p2("b",20);
person p3("c",30);
person p4("d",40);
Myarray<person>arr1(10);
arr1.push_back(p1);
arr1.push_back(p2);
arr1.push_back(p3);
arr1.push_back(p4);
arrayprint(arr1);
}
void main()
{
test();
}
实现结果: