C++程序设计课程介绍-第13章 泛型机制—模板

上传人:aa****6 文档编号:48655675 上传时间:2018-07-19 格式:PPT 页数:43 大小:128KB
返回 下载 相关 举报
C++程序设计课程介绍-第13章 泛型机制—模板_第1页
第1页 / 共43页
C++程序设计课程介绍-第13章 泛型机制—模板_第2页
第2页 / 共43页
C++程序设计课程介绍-第13章 泛型机制—模板_第3页
第3页 / 共43页
C++程序设计课程介绍-第13章 泛型机制—模板_第4页
第4页 / 共43页
C++程序设计课程介绍-第13章 泛型机制—模板_第5页
第5页 / 共43页
点击查看更多>>
资源描述

《C++程序设计课程介绍-第13章 泛型机制—模板》由会员分享,可在线阅读,更多相关《C++程序设计课程介绍-第13章 泛型机制—模板(43页珍藏版)》请在金锄头文库上搜索。

1、第13章 泛型机制模板n类模板的定义 n类模板的实例化 n模板的编译 n非类型形参和参数的默认值 n类模板的友元 n类模板作为基类 类模板的定义n类模板允许用户为类定义一种模式,使得类中的某些数据成员、某些成员函数的参数或返回值能取任意数据类型。n定义格式:template class Array int low; int high;T *storage; public:Array(int lh = 0, int rh = 0): low(lh), high(rh)storage = new T high - low + 1; Array(const Array Array T Array()

2、 delete storage; ;类模板的成员函数的定义 n类模板的成员函数都是函数模板,模板参数与类模板相同n形式: Template返回类型 类模板名:成员函数名(函数的形参表)函数体nArray类的成员函数的格式 template 返回类型 Array:函数名(形式参数表)函数体Array的成员函数的实现 template Array /防止自己复制自己delete storage; / 归还空间low = a.low;high = a.high;storage = new T high - low + 1; for (int i=0; i Array:Array(const Arra

3、y high = arr.high;storage = new T high - low + 1;for (int i = 0; i T Array array2(10, 20);模板类的对象的使用n我们可以用下列语句输入array2的值:for (i=10; i class Array T storagehigh - low + 1; public: T ;template T 参数的默认值n模板参数和普通的函数参数一样,也可 以指定默认值。如果前例中的类模板 Array经常被实例化为整型数组,则可在 类模板定义时指定缺省值: template class Array ;n当要定义整型数组a

4、rray时,就可以不指 定模板的实参: Arraynext, *q;head-next=NULL;while (p != NULL) q=p-next; delete p; p=q; template void linkList:create(const elemType node *p, *q = head;cout tmp;if (tmp = flag) break;p = new node(tmp);q-next = p;q = p;q-next = NULL; linkList类模板中的输出运算符重载 函数的实现template ostream os data; q = q-next;

5、 return os;链表类的使用n定义: linkList intList;该定义产生了类模板的一个整型实例n如果想创建这个单链表,可以调用create函数 : intList.create(0);该调用将输入链表中的元素值,直到输入0为止。n要输出链表的所有元素,可以直接输出: cout class stack : public linkList public:void push(const elemType p-next = head-next; head-next = p;bool pop(elemType if ( p = NULL) return false;head-next =

6、 p-next; data = p-data; delete p;return true; ; 类模板stack的使用n定义一个整型栈:stack st; n进栈:for (int i = 1; i 10; +i) st.push(i);n出栈: while (st.pop(i) cout i t;n执行结果:9 8 7 6 5 4 3 2 1小结 n本章介绍了C+中的泛型程序设计的工 具-模板。n模板是独立于类型的蓝图,编译器可以 根据模板产生多种特定类型的实例。n模板分为函数模板和类模板。n本章中,我们学习了如何写一个类模板 ,如何实例化类模板,使之成为一个模 板类,如何定义及使用模板的友元。

展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 办公文档 > 其它办公文档

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