自定义数组类

#ifndef CLASS_ARRAY
#define CLASS_ARRAY

#include<iostream>
#include<cstdlib>
using namespace std;

enum Error
{
 Invalid_Size,Allocation_Error,Out_Of_Bound 
};

enum Mode
{
 Change,Append
};
 
char *ErrorMsg[]={"Invalid Array Size","Memory Allocation Error","Index Out Of Bound"};

template<class T>
class Array
{
private:
 T *content;
 int size;
 void ErrorExit(Error type);
public:
 Array(int n=10);
 Array(Array<T> &source);
 ~Array();

 Array<T>& operator =(Array<T> &source);
 T& operator [](int index);
 operator T*();

 int PeekSize();
 void Resize(int n,Mode mode=Change);
};

template<class T>
void Array<T>::ErrorExit(Error type)
{
 std::cout<<ErrorMsg[type]<<endl;
 exit(0);
}

template<class T>
Array<T>::Array(int n)
{
 if(n<0) ErrorExit(Invalid_Size);
 content=new T[n];
 if(content==NULL) ErrorExit(Allocation_Error);
 size=n;
  
}

template<class T>
Array<T>::Array(Array<T> &source)
{
 size=source.size;
 content=new T[size];
 for(int i=0;i<size;i++){content[i]=source.content[i];}
 return *this;
}

template<class T>
Array<T>::~Array()
{
 if(content!=NULL) delete []content;
}


template<class T>
Array<T>& Array<T>::operator =(Array<T> &source)
{
 if(size<source.size)
 {
  delete []content; 
  size=source.size;
  content=new T[size];
 }
 
 for(int i=0;i<size;i++){content[i]=source.content[i];}
 return *this;
}

template<class T>
T& Array<T>::operator [](int index)
{
 if (index<0||index>=size) ErrorExit(Out_Of_Bound);
 return content[index];
}

template<class T>
Array<T>::operator T*()
{
 return content;
}

template<class T>
int Array<T>::PeekSize()
{
 return size;
}

template<class T>
void Array<T>::Resize(int n,Mode mode)
{
 if(n<0) ErrorExit(Invalid_Size);
 int t;
 if(mode==Change)
  t=n;
 else
  t=n+size;
 
 T* temp=new T[t];
 if (temp==NULL) ErrorExit(Allocation_Error);

 int end=(t>size)?size:t;

 for(int i=0;i<end;i++) temp[i]=content[i];
 delete []content;
 size=t;
 content=temp;
}

#endif

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值