模版的意思是,按不同的方式重复使用相同的代码。
一个类模板(也称为类属类或类生成类)允许用户定义为类定义的一种模式,是的类中的某些数据成员、默写成员函数的参数、某些成员函数的返回值,能够取任意类型,包括系统预定义的和用户自定义的
类模板的格式是
template <模板参数表>
class (类名)
{
(类型说明)
};
下面是数组模板的具体实现;
template<class T>
class MyArry
{
public:
explicit MyArry(int capacity)
arr =10 ;
{
this->m_Capacity = capacity;
this->m_Size = 0;
this->Address = new T[this->m_Capacity];
}
MyArry(const MyArry & arry)
{
this->m_Capacity = arry.m_Capacity;
this->m_Size = arry.m_Size;
this->Address = new MyArry[this->m_Capacity];
for (int i = 0; i < arry.m_Size; i++) {
this->Address[i] = arry[i];
}
}
MyArry()
{
if (this->Address != NULL) {
delete[] this->Address;
this->Address = NULL;
}
}
MyArry & operator =(const MyArry & arr)
{
if (this->Address != NULL) {
delete[] this->Address;
this->Address = NULL;
}
this->m_Capacity = arr.m_Capacity;
this->m_Size = arr.m_Size;
this->Address = new MyArry[this->m_Capacity];
for (int i = 0; i < arr.m_Size; i++) {
this->Address[i] = arr[i];
}
}
T & operator[](int index)
{
return this->Address[index];
}
void push_Back(T val)
{
this->Address[this->m_Size] = val;
this->m_Size++;
}
int getSize(MyArry & arr)
{
return this->m_Size;
}
int getCapacity(MyArry & arr)
{
return this->m_Capacity;
}