#include<iostream> #include <string> using namespace std; template <class T>//使用模板函数 class myarr { public: myarr(int n)//有参构造 { this->C = n; this->size = 0; this->p = new T[C]; } myarr(const myarr& other)//复制构造 { this->C = other.C; this->size = other.size; this->p = new T[other.C];//防止重复释放空间 for (int i = 0; i < size; i++) p[i] = other[i]; } ~myarr() { if (this->p != NULL)//判断P是否为空,然后delete { delete[]this->p; this->p = NULL;//防止p变成野指针 } } void push_back(const T& num)//将数据存入myarr中 { if (this->C == this->size)//如果超过容量就return return; this->p[this->size] = num; this->size++; } void pop_back()//尾删法,使size减一 { if (this->size == 0) return; this->size--; } myarr& operator=(const myarr& other)//重载等号,要深复制,方式p重复释放空间 { if (this->p != NULL) { delete[]this->p; } this->C = other.C; this->size = other.size; this->p = new T[other.C]; for (int i = 0; i < size; i++) p[i] = other[i]; return *this; } T& operator[](int index)//重载[] { return this->p[index]; } int getC()//获取容量 { return this->C; } int getsize()//获取数组大小 { return this->size; } private: T* p; int size; int C; }; class base//用base类进行测试myarr { public: base() :name("null"), age(0) { } base(string n, int a) { this->age = a; this->name = n; } void show()const { cout << "名字: " << name << " 年龄: " << age; } ~base() {} private: string name; int age; }; void myprintf( myarr<base>&m)//用于打印base类的数组 { for (int i = 0; i < m.getsize(); i++) { m[i].show(); cout << endl; } cout <<"myarr的容量"<< m.getC() << endl; cout <<"myarr的大小"<< m.getsize() << endl; } void test()//测试案例 { base b1("zhangshan", 100); myarr<base>a(5); for(int i=0;i<5;i++) a.push_back(b1); myprintf(a); cout<<endl; a.pop_back(); myprintf(a); } int main() { test(); return 0; }
代码运行截图