类模板-template
来源:互联网 发布:兄弟连php课程大纲 编辑:程序博客网 时间:2024/06/06 10:51
template是声明各模板的关键字,表示声明一个模板,模板参数可以是一个,也可以是多个。
声明类模板要增加一行: template<class 类型参数名>
如template<class dataType>其中的类型参数名为虚拟的类型参数名,以后会被实际的类型名替代。如例子中的dataType将会被int,float,char等替代。
class Compare_int{private:int x,y;public:Compare(int a,int b){x=a;y=b;}int getMax(){return (x>y)? x:y;}};class Compare_float{private:float x,y;public:Compare(float a,float b){x=a;y=b;}float getMax(){return (x>y)? x:y;}};class Compare_float{private:float x,y;public:Compare(float a,float b){x=a;y=b;}float getMax(){return (x>y)? x:y;}};用一个类模板减少重复性的工作:template<class dataType>class Compare{private:dataType x,y;public:Compare(dataType a,dataType b){x=a;y=b;}dataType getMax(){return (x>y)? x:y;}};
实例化时必须用实际的类型名去替代虚拟的类型,如Compare<int> cmp1(3,7);
完整代码:
#include <iostream>using namespace std;template<class dataType>class Compare{private:dataType x,y;public:Compare(dataType a,dataType b){x=a;y=b;}dataType getMax(){return (x>y)? x:y;}};int main(){Compare<int> cmp1(3,7);cout<<cmp1.getMax()<<" is the Maximum of two Integer numbers"<<endl;Compare<float> cmp2(12.3,23.4);cout<<cmp2.getMax()<<" is the Maximun of two Float numbers"<<endl;Compare<char> cmp3('a','b');cout<<cmp3.getMax()<<" is the Maximun of two Char numbers"<<endl;return 0;}
0 0
- C++ template - 类模板
- template 模板类
- c++ template 类模板
- C++类模板template
- 类模板-template
- C++模板类template
- template模板类使用
- 类模板Template
- C++类模板template
- c++ template 类模板特化
- 类模板template的使用!
- C++中的类模板Template
- C++template 模板类2
- C++模板类(Template)
- template模板类和模板函数
- (一)函数模板与类模板 Template
- C++,template,类模板和函数模板
- 模板Template
- Java实现HMacMD5加密,用于淘宝客JS 组件 API 调用时生成 sign 的签名
- 解决Visual Stuido 2010/2012/2013中Mono For Android *.axml文件没有智能提示问题
- grep 命令查找文件中的文本字符串
- java初体验学习笔记
- Linux网络设置(第二版) --Linux网络设置
- 类模板-template
- ubuntu系统远程环境搭建
- linux设置mysqlwait_timeout时间
- C++ 实现k-means machine learning 算法 Computer Vision
- ARP:地址解析协议实现学习
- CF_#268_DIV2_A_B_D
- HDU 1005 Number Sequence (循环节)
- Oracle RMAN备份单个文件的并发执行
- HDU 5025 Saving Tang Monk(bfs)