文档详情

PPTC++模板介绍.ppt

发布:2017-04-21约2.63千字共22页下载文档
文本预览下载声明
C++模板;提纲;模板引子;模板的概念;模板分类;求最大值模板函数实现;模板工作方式;#include iostream.h template class T T min(T a[],int n) { int i; T minv=a[0]; for( i = 1;i n ; i++){ if(minva[i]) minv=a[i]; } return minv; };在函数模板中允许使用多个类型参数。但在template定义部分的每个模板形参前必须有关键字class。; 在template语句与函数模板定义语句之间不允许有别的语句。 //这是不能编译的 Template class T int i; //错误,不允许有别的语句 T max(T x,T y) { return(xy)? x : y;} 模板函数类似于重载函数,只不过它更严格一些而已。函数被重载的时候,在每个函数体内可以执行不同的动作,但同一函数模板实例化后的所有模板函数都必须执行相同的动作。 //不能做函数模板的 void outdate(int i) { couti; } void outdata(double d) {cout”d=”dendl;} ;模板优缺点;类模板和模板类;例: 下面的程序中建立了一个用来实现堆栈的类模板。 const int size=10 Templateclass Type class stack{ Type stck[size]; int top; public: void init() {top=0;} void push(Type ch); Type pop(); };; 成员函数 push() 和 pop() 在类定义体外定义,如果该成员函数中有模板参数,则需先进行模板声明,再用类模板名来限定函数名,即在函数名前,类名后缀上“Type” templateclass Type void stackType::push(Type ob) { if(top= =size) { cout”stack is full”; return; } stck[top]=ob; top++; };templateclass Type Type stackType::pop() { if(top= =0) { cout”stack is empty”; return 0; } tos--; return stck[top]; };类模板stack(Type);例 类模板stack的例子,在此建立了字符型和整型两个堆栈。;templateclass Type void stackType::push(Type ob) { if (top= =size) { cout”stack is full”; return; } stck[top]=ob; top++; } templateclass Type Type stackType::pop() { if (top= =0) { cout”stack is empty”; return 0; } top--; return stck[top]; };void main() { //定义字符堆栈 stackchars1,s2; int i; s1.init(); s2.init(); s1.push(‘a’); s2.push(‘x’); s1.push(‘b’); s2.push(‘y’); s1.push(‘c’); s2.push(‘z’); for(i=0;i3;i++) cout”pops1:”s1.pop()endl; for(i=0;i3;i++) cout”pops2:”s2.pop()endl; ;//定义整型堆栈 stackintis1,is2; //创建两个模板参数为int型的对象 is1.init(); is2.init(); is1.push(1); is2.push(2); is1.push(3); is2.push(4); is1.push(5); is2.push(6);
显示全部
相似文档