《lesson09》由会员分享,可在线阅读,更多相关《lesson09(11页珍藏版)》请在金锄头文库上搜索。
1、第九章 模板1模板l函数模板l类模板2函数模板l函数模板可以用来创建一个通用功能 的函数,以支持多种不同形参,进一步 简化重载函数的函数体设计。l声明方法:template 函数声明函 数 模 板3求绝对值函数的模板#include using namespace std; template T abs(T x) return x class 类名 类成员声明l如果需要在类模板以外定义其成员 函数,则要采用以下的形式: template 类型名 类名:函数名(参数表 )类 模 板7类模板应用举例#include #include using namespace std; / 结构体Studen
2、t struct Student int id; /学号float gpa; /平均分 ; 类 模 板8template /类模板:实现对任意类型数据进行存取 class Store private:T item; / 用于存放任意类型的数据int haveValue; / 用于标记item是否已被存入内容public:Store(void); / 默认形式(无形参)的构造函数T GetElem(void); /提取数据函数void PutElem(T x); /存入数据函数 ;/ 默认形式构造函数的实现 template Store:Store(void): haveValue(0) 99t
3、emplate / 提取数据函数的实现 T Store:GetElem(void) / 如果试图提取未初始化的数据,则终止程序if (haveValue = 0) cout / 存入数据函数的实现 void Store:PutElem(T x) haveValue+; / 将haveValue 置为 TRUE,表 示item中已存入数值item = x; / 将x值存入item 1010void main(void) Student g= 1000, 23; Store S1, S2; Store S3;Store 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的数据成员1111