类模板的应用--用类模板实现动态数组

template<class T>
class DynamicArray
{
public:
T* ptrt;
int tcapacity;
int tsize;
public:
DynamicArray()
{
this->tcapacity = 5;
this->tsize = 0;
this->ptrt = new T[tcapacity];
}
~DynamicArray()
{
if (ptrt != NULL)
delete[] this->ptrt;
}
void InseetAtEnd(T t)//在尾部插入
{
if (this->tsize == this->tcapacity)
{
this->tcapacity += 5;
T* tmp;
tmp = new T[this->tcapacity];
int i;
for (i = 0;i < this->tsize;i++)
{
tmp[i] = this->ptrt[i];
}
delete[] this->ptrt;
this->ptrt = tmp;
}
this->ptrt[this->tsize] = t;
this->tsize++;
}
T& operator[](int index)//重载[]
{
return this->ptrt[index];
}
};
class Info
{
public:
int ID;
string name;
Info(int id,string str)
{
this->ID = id;
this->name = str;
}
Info() {};
};
void ForEach(DynamicArray<Info>& dynamicarr)
{
int i = 0;
for (;i < dynamicarr.tsize;i++)
{
cout << dynamicarr[i].name<<"   "<<endl;
}
cout << endl;
}
void test()
{
DynamicArray<Info> dynamicarr;
Info I1(1, "aa"), I2(2, "bb"), I3(3, "cc"), I4(4, "dd"), I5(5, "ee"), I6(6, "ff");
dynamicarr.InseetAtEnd(I1);dynamicarr.InseetAtEnd(I2);dynamicarr.InseetAtEnd(I3);
dynamicarr.InseetAtEnd(I4);dynamicarr.InseetAtEnd(I5);dynamicarr.InseetAtEnd(I6);
ForEach(dynamicarr);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值