0
点赞
收藏
分享

微信扫一扫

C++语言基础 例程 类模板

一ke大白菜 2022-03-17 阅读 82


类模板的使用——参数化类

#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;
}




举报

相关推荐

0 条评论