C++语言程序设计 清华大学郑莉 数组 直 接°静态数组是具有固定元素个数的群体,其 T万 中的元素可以通过下标直接访问 缺点:大小在编译时就已经确定,在运 行时无法修改。 的 线动态数组由一系列位置连续的,任意数量 相同类型的元素组成。 性 优点:其元素个数可在程序运行时改变。 琳动态数组类模板603(03h)x
C++语言程序设计 清华大学 郑莉 16 数组 ⚫ 静态数组是具有固定元素个数的群体,其 中的元素可以通过下标直接访问。 – 缺点:大小在编译时就已经确定,在运 行时无法修改。 ⚫ 动态数组由一系列位置连续的,任意数量 相同类型的元素组成。 – 优点:其元素个数可在程序运行时改变。 ⚫ 动态数组类模板:例9-3(9_3.h) 直 接 访 问 的 线 性 群 体
ifndef array class define ARRAY CLAss 动态杰数组类模板程序 using names pace std; include <iostream> include <cstdlib> ifndef NULl const int NULL 0: # endif∥NULL enum ErrorType [ invalidArraySize, memoryAllocation Error indexOutofRange 3 char *errorMsgl i"Invalid array size", Memory allocation error Invalid index }
#ifndef ARRAY_CLASS #define ARRAY_CLASS using namespace std; #include <iostream> #include <cstdlib> #ifndef NULL const int NULL = 0; #endif // NULL enum ErrorType { invalidArraySize, memoryAllocationError, indexOutOfRange }; char *errorMsg[] = { "Invalid array size", "Memory allocation error", "Invalid index: " }; 动态数组类模板程序 17
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); 18
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); }; 18
C++语言程序设计 清华大学郑莉 数组类模板的构造巫数 直 ∥构造函数 接 template< class t 心【<T: Array(int sz) 访Ar if (sz <= 0) 的 ∥fz为数组大小(元素个数),若小于0,则输出错误信息 Error(invalidArray Size) 线 性 size=sz;∥将元素个数赋值给变量size ait=newT[sze];l动态分配sze个T类型的元素空间 群if(list==NUL)∥如果分配内存不成功,输出错误信息 体 Error(memory Allocation Error);
C++语言程序设计 清华大学 郑莉 19 数组类模板的构造函数 // 构造函数 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); } 直 接 访 问 的 线 性 群 体
C++语言程序设计 清华大学郑莉 数组类的拷贝构造函数 直 接 emplate sclass o>(y<T>: Array(const Array<T>& X T万 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++;
C++语言程序设计 清华大学 郑莉 20 数组类的拷贝构造函数 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++; } 直 接 访 问 的 线 性 群 体