您的位置:首页 > 编程语言 > C语言/C++

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: