C++语言程序设计 湖南科技大学 数组 直 接静态数组是具有固定元素个数的群体, T万 其中的元素可以通过下标直接访问 缺点:大小在编译时就已经确定, 的 在运行时无法修改。 线动态数组由二系列位置连续的,任意 性 数量相同类型的元素组成。 群 优点:其元素个数可在程序运行时 体改变
C++语言程序设计 湖南科技大学 16 数组 ⚫ 静态数组是具有固定元素个数的群体, 其中的元素可以通过下标直接访问。 –缺点:大小在编译时就已经确定, 在运行时无法修改。 ⚫ 动态数组由一系列位置连续的,任意 数量相同类型的元素组成。 –优点:其元素个数可在程序运行时 改变。 直 接 访 问 的 线 性 群 体
动态数组类模板:例9-3(93h) #ifndef ARRAY CLASS define array class using name space std #include <iostream> #include <cstdlib) #ifndef NULL const int Null=0 #endif // NULI enum Errorlype i invalidArraySize, memoryAllocationError indexOutOfRange char米 errorS[ Invalid array size",Memory allocation error Invalid index: I 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 ⚫ 动态数组类模板:例9-3(9_3.h)
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 1) 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 K<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++语言程序设计 湖南科技大学 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> 332 Array<T>: Array(const Array<T>& X) T万 int n=x size SIZe-n 的线性群体 的alst= new TLn]; if (alist==NULL Error(memoryAllocationError) T* srcptr=X. alist;//x. alist是对象X的数组首地址 T* destptr= alist;//a1ist是本对象中的数组首地址 while(n //逐个复制数组元素 *destptr++ * ksrcptr++
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++; } 直 接 访 问 的 线 性 群 体