文档详情

c++9模板-群体类和群体数据组织.ppt

发布:2017-07-06约7.79千字共80页下载文档
文本预览下载声明
第九章 群体类 和群体数据的组织;本章主要内容;第一部分—模板;函数模板;求绝对值函数的模板;求绝对值函数的模板分析;类模板的作用;类模板的声明;例9-2 类模板应用举例;template class T //类模板:实现对任意类型数据进行存取 class Store { private: T item; // 用于存放任意类型的数据 int haveValue; // 用于标记item是否已被存入内容 public: Store(void); // 默认形式(无形参)的构造函数 T GetElem(void); //提取数据函数 void PutElem(T x); //存入数据函数 }; // 默认形式构造函数的实现 template class T StoreT::Store(void): haveValue(0) {};template class T // 提取数据函数的实现 T StoreT::GetElem(void) { // 如果试图提取未初始化的数据,则终止程序 if (haveValue == 0) { cout No item present! endl; exit(1); } return item; // 返回item中存放的数据 } template class T // 存入数据函数的实现 void StoreT::PutElem(T x) { haveValue++; // 将haveValue 置为 TRUE,表示item中已存入数值 item = x; // 将x值存入item };void main(void) { Student g= {1000, 23}; Storeint S1, S2; StoreStudent S3; Storedouble D; S1.PutElem(3); S2.PutElem(-7); cout S1.GetElem() S2.GetElem() endl; S3.PutElem(g); cout The student id is S3.GetElem().id endl; cout Retrieving object D ; cout D.GetElem() endl; //输出对象D的数据成员 // 由于D未经初始化,在执行函数D.GetElement()时出错 };第二部分—群体数据;群体的概念;线性群体的概念;数组;#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: };;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 ArrayT A); ~Array(void); ArrayT operator= (const ArrayT rhs); T operator[](int i); operator T* (void) const; int ListSize(void) const; void Resize(int sz);
显示全部
相似文档