C++设计一个数组模板,可以存贮任意类型数组

模版的意思是,按不同的方式重复使用相同的代码。

一个类模板(也称为类属类或类生成类)允许用户定义为类定义的一种模式,是的类中的某些数据成员、默写成员函数的参数、某些成员函数的返回值,能够取任意类型,包括系统预定义的和用户自定义的

类模板的格式是 

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;

   }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值