C++类模板之小实例(1)
来源:互联网 发布:淘宝客服企业介绍范文 编辑:程序博客网 时间:2024/05/29 02:19
模板是面向对象技术提高软件开发效率的重要手段,是C++语言的重要特征。函数模板可根据函数实参的类型,实例化成相应的具体函数,以处理不同类型的函数。
类模板的定义有两种形式:
类模板的成员函数既可以在类内声明类内实现,也可以在类内声明,在类外实现。注意两种不同的表达方式。
下面是一个完整实例
声明一个类模板,实现比较int型,float型和char型的两个变量的大小:
#include <iostream> using namespace std; template <class numtype>//定义类模板class Compare{ private : numtype x,y; public : Compare(numtype a,numtype b) {x=a;y=b;} numtype max( ) {return (x>y)?x:y;} numtype min( ) {return (x<y)?x:y;} };int main( ){ Compare<int > cmp1(3,7);//定义对象cmp1,用于两个整数的比较 cout<<cmp1.max()<<"is the Maximum of two integer numbers ."<<endl; cout<<cmp1.min( )<<"is the Minimum of two integer numbers."<<endl<<endl; Compare<float > cmp2(45.78,93.6); //定义对象cmp2,用于两个浮点数的比较 cout<<cmp2.max( )<<"is the Maximum of two float numbers."<<endl; cout<<cmp2.min( )<<"is the Minimum of two float numbers."<<endl<<endl; Compare<char> cmp3('a','A'); //定义对象cmp3,用于两个字符的比较 cout<<cmp3.max( )<<"is the Maximum of two characters."<<endl; cout<<cmp3.min( )<<"is the Minimum of two characters."<<endl; return 0;} #include <iostream> using namespace std; template <class numtype>//定义类模板class Compare{ private : numtype x,y; public : Compare(numtype a,numtype b) {x=a;y=b;} numtype max( ); numtype min( );}; template <class numtype>numtype Compare <numtype>:: max(){ {return (x>y)?x:y;}}template <class numtype>numtype Compare <numtype>:: min(){ {return (x<y)?x:y;}}int main( ){ Compare<int > cmp1(3,7);//定义对象cmp1,用于两个整数的比较 cout<<cmp1.max()<<"is the Maximum of two integer numbers ."<<endl; cout<<cmp1.min( )<<"is the Minimum of two integer numbers."<<endl<<endl; Compare<float > cmp2(45.78,93.6); //定义对象cmp2,用于两个浮点数的比较 cout<<cmp2.max( )<<"is the Maximum of two float numbers."<<endl; cout<<cmp2.min( )<<"is the Minimum of two float numbers."<<endl<<endl; Compare<char> cmp3('a','A'); //定义对象cmp3,用于两个字符的比较 cout<<cmp3.max( )<<"is the Maximum of two characters."<<endl; cout<<cmp3.min( )<<"is the Minimum of two characters."<<endl; return 0;}
- C++类模板之小实例(1)
- C++模板类之小实例(2)
- C++(33)模板与泛型之实例化
- 模板实例化(c++)
- [C++] C++小笔记之模板函数
- C++primer学习:类模板(1):函数模板,模板参数,实例化
- c++(1) 类模板/构造函数/捕获异常 实例
- C++中类模板实例
- [C++]类模板在何时实例化?
- C++ Template学习笔记之函数模板(2)——函数模板实例化
- C++ Template学习笔记之函数模板(2)——函数模板实例化
- 模板的一个小实例
- C++primer学习:类模板(2)类模板:模板参数,成员模板和控制实例化
- 工作积累之模板类实例化
- 工作积累之模板类实例化
- C++之模板类stack实例
- C++之模板使用实例(一)
- c语言小程序实例(一)
- 计算机视觉相关领域网站链接(转)
- android发送短信
- Python解析xml-pybatis的准备阶段(八)
- 一个Ruby小程序
- LeetCode Convert Sorted List to Binary Search Tree
- C++类模板之小实例(1)
- Arrays类——Arrays.asList()方法使用
- S3C2440系统时钟
- 编程是一门技术,更加是一门艺术
- STM32-串口超时判断方式接收未知长度数据
- Java异常:Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion;
- 学习进程之命令ps(一)
- Android基础控件之单选框(RadioButton)
- Apache整合Tomcat