C++语言基础 例程 类模板
2015-04-07 10:27
525 查看
贺老师的教学链接 本课讲解
类模板的使用——参数化类
在类模板外定义成员函数
类库中的模板
类模板的使用——参数化类
#include <iostream> using namespace std; template<class numtype> class Compare { public: Compare(numtype a,numtype b) { x=a; y=b; } numtype max( ) { return (x>y)?x:y; } numtype min( ) { return (x<y)?x:y; } private: numtype x,y; }; int main( ) { Compare<int> cmp1(3,7); 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); 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'); 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 { public: Compare(numtype a,numtype b); numtype max( ); numtype min( ); private: numtype x,y; }; template<class numtype> Compare<numtype>::Compare(numtype a,numtype b) { x=a; y=b; } 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); cout<<cmp1.max( )<<" is the Maximum of two integer numbers."<<endl; cout<<cmp1.min( )<<" is the Minimum of two integer numbers."<<endl<<endl; Compare<double> cmp2(45.78,93.6); 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'); cout<<cmp3.max( )<<" is the Maximum of two characters."<<endl; cout<<cmp3.min( )<<" is the Minimum of two characters."<<endl; return 0; }
类库中的模板
#include<vector> #include <iostream> using namespace std; int main() { int i = 0; vector<int> v; for( i = 0; i < 10; i++ ) { v.push_back(i);//把元素一个一个存入到vector中 } /* v.clear() 对存入的数据清空*/ for( i = 0; i < v.size(); i++ )//v.size() 表示vector存入元素的个数 { cout << v[i] << " "; //把每个元素显示出来 } cout << endl; return 0; }
相关文章推荐
- C++语言基础 例程 函数模板
- C++语言基础 例程 类的成员函数
- C++语言基础 例程 默认构造函数
- C++语言基础 例程 应用系统开发:银行储蓄系统
- C++语言基础 例程 不同类型数据间的转换
- C++语言基础 例程 重载单目运算符
- C++语言基础 例程 对象成员的引用
- C++语言基础 例程 静态成员
- C++语言基础 例程 函数中的引用
- C++语言基础 例程 深复制
- C++语言基础 例程 案例:MyVector类的设计
- C++语言基础 例程 类声明和成员函数定义的分离
- C++语言基础 例程 类的声明和对象的定义
- C++语言基础 例程 用const实施保护
- C++语言基础 例程 析构函数
- C++语言基础 例程 运算符重载的方法
- C++语言基础 例程 构造函数
- C++语言基础 例程 对象数组
- C++语言基础 例程 重载流插入运算符和流提取运算符
- C++语言基础 例程 重载双目运算符