#include <iostream.h>#include <stdlib.h>//容錯(cuò)處理enum ErrorType{invalidArraySize,memoryAllocatetionError,indexOutOfRang};char *errorMsg[] ={"Invalid array size","Memory allocation error","Invalid index"};template <class T>class Array{private:T* alist;int size;void Error(ErrorType error) const;//輸出錯(cuò)誤信息public:Array(int sz=50);//構(gòu)造函數(shù)Array(const Array<T>& X);//拷貝構(gòu)造函數(shù)~Array(void);//析構(gòu)函數(shù)Array<T>& operator=(const Array<T>& rhs);//重載賦值運(yùn)算符T& operator[](int i);//重載下標(biāo)運(yùn)算符int GetSize(void) const;//獲取數(shù)組大小void Resize(int sz);//重新設(shè)置數(shù)組大小};template <class T>Array<T>::Array(int sz){if(sz <= 0)? Error(invalidArraySize);size = sz;alist = new T[size];if(alist == 0)? Error(memoryAllocatetionError);}template <class T>Array<T>::Array(const Array<T>& X){int n = X.size;size = n;alist = new T[n];if(alist == 0)? Error(memoryAllocatetionError);T* srcptr = X.alist;T* destptr = alist;while(n--)? *destptr++ = *srcptr++;}template<class T>Array<T>::~Array(){delete[] alist;}template <class T>Array<T>& Array<T>::operator=(const Array<T> &rhs){int n = rhs.size;if(size != n){? delete[] alist;? alist = new T[n];? if(alist == 0)?? Error(memoryAllocatetionError);? size = n;}T* destptr = alist;T* srcptr = rhs.alist;while(n--)? *destptr++ = *srcptr++;return *this;}template<class T>T& Array<T>::operator[](int n){if(n < 0 || n > size-1)? Error(indexOutOfRang);return alist[n];}void main(){}
- 0 回答
- 0 關(guān)注
- 1544 瀏覽
添加回答
舉報(bào)
0/150
提交
取消