lesson09

上传人:第*** 文档编号:51255614 上传时间:2018-08-13 格式:PPT 页数:11 大小:112.50KB
返回 下载 相关 举报
lesson09_第1页
第1页 / 共11页
lesson09_第2页
第2页 / 共11页
lesson09_第3页
第3页 / 共11页
lesson09_第4页
第4页 / 共11页
lesson09_第5页
第5页 / 共11页
点击查看更多>>
资源描述

《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

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 中学教育 > 教学课件 > 初中课件

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号