C++语言程序设计 清华大学郑莉 数组 ● 静态数组是具有固定元素个数的群体,其 直接访问的线性群 中的元素可以通过下标直接访问。 缺点:大小在编译时就已经确定,在运 行时无法修改。 ● 动态数组由一系列位置连续的,任意数量 相同类型的元素组成。 -优点:其元素个数可在程序运行时改变。 ● 动态数组类模板:例9-3(93.h) 体 16
C++语言程序设计 清华大学 郑莉 16 数组 ⚫ 静态数组是具有固定元素个数的群体,其 中的元素可以通过下标直接访问。 – 缺点:大小在编译时就已经确定,在运 行时无法修改。 ⚫ 动态数组由一系列位置连续的,任意数量 相同类型的元素组成。 – 优点:其元素个数可在程序运行时改变。 ⚫ 动态数组类模板:例9-3(9_3.h) 直 接 访 问 的 线 性 群 体
#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
#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 private: T*alist; int size; void Error(ErrorType error,int badlndex=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
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> Array<T>::Array(int sz) if (sz <0) sz为数组大小(元素个数),若小于0,则输出错误信息 的线性群体 Error(invalidArray Size); size=sz;∥将元素个数赋值给变量size alist=newT[size];/动态分配size个T类型的元素空间 if(alist=NULL)/如果分配内存不成功,输出错误信息 Error(memoryAllocationError); } 19
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++语言程序设计 清华大学郑莉 数组类的拷贝尥造函数 接 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++; 20
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++; } 直 接 访 问 的 线 性 群 体