动数组类模板 直 接·数组类模板: 访例91(91h) 线性群体 休息
前一页 休息 6 动态数组类模板 ⚫ 数组类模板: 例9.1(9_1.h) 直 接 访 问 线 性 群 体
ifndef array class define ArraY CLass Include <iostream h> include <stdlib. h> ifndef null const int nUll〓0 # endif∥NULL enum ErrorType IinvalidArraySize, memory Allocation Error, indexOutofRange 3 char *errorMMsgn i"Invalid array size ,"Memory allocation error Invalid index. }
#ifndef ARRAY_CLASS #define ARRAY_CLASS #include <iostream.h> #include <stdlib.h> #ifndef NULL const int NULL = 0; #endif // NULL enum ErrorType { invalidArraySize, memoryAllocationError, indexOutOfRange }; char *errorMsg[] = { "Invalid array size", "Memory allocation error", "Invalid index: " };
template <class T> class Array I private T* alist. int size: void Error(ErrorType error, int badIndexe=0) const public Arrayint sz= 50); Array(const Array <T>&A); rArray(void); Array<T>& operator=(const Array <T>& rhs); T& operator (int i; operator T*(void) const int Listsize(void) const; void Resize(int sz);
template <class T> class Array { private: T* alist; int size; void Error(ErrorType error,int badIndex=0) const; public: Array(int sz = 50); Array(const Array<T>& A); ~Array(void); Array<T>& operator= (const Array<T>& rhs); T& operator[](int i); operator T* (void) const; int ListSize(void) const; void Resize(int sz); };
数组类模板部分成员函数的奥现 ∥构造函数 template <class T> f ysT>:: Array(int sz) Array if (sz<=0) ∥sz为数组大小(元素个数),若小于0,则输出错误信息 Error(invalidArray Size); size=sz;∥将元素个数赋值给变量size ait=newT[sze];动态分配sze个T类型的元素空间 if (alist==NUL)∥如果分配内存不成功,输出错误信息 Error(memory Allocation Error); 了一页休息
前一页 休息 9 数组类模板部分成员函数的实现 // 构造函数 template <class T> Array<T>::Array(int sz) { if (sz <= 0) //sz为数组大小(元素个数),若小于0,则输出错误信息 Error(invalidArraySize); size = sz; // 将元素个数赋值给变量size alist = new T[size]; //动态分配size个T类型的元素空间 if (alist == NULL) //如果分配内存不成功,输出错误信息 Error(memoryAllocationError); }
拷贝构造函数 template <class T> fysT:: Array(const Array<T>& X) Arra int n= X. size: SIze E n alist= new Tin if (alist== NULL) Error(memory Allocation Error) T srcptr= X alist;∥ Xalist是对象X的数组首地址 T* destptr=aist;∥ alist是本对象中的数组首地址 while(n--) ∥逐个复制数组元素 destptr++=‘ srcptr++; 了一页休息
前一页 休息 10 拷贝构造函数 template <class T> Array<T>::Array(const Array<T>& X) { int n = X.size; size = n; alist = new T[n]; if (alist == NULL) Error(memoryAllocationError); T* srcptr = X.alist; // X.alist是对象X的数组首地址 T* destptr = alist; // alist是本对象中的数组首地址 while (n--) // 逐个复制数组元素 *destptr++ = *srcptr++; }