模板意思:把数据类型当作参数

 

#include<iostream>
using namespace std;


template <class T>              //函数模板
T mymax(T a, T b)
{
if (a > b)
return a;
else
return b;
}


template <class T>         //类模板
class Person
{
public:
T a;
T b;
Person()
{};
Person(T x, T y);
T XMax();
};

template <class T>                                   
Person<T>::Person(T x, T y):a(x),b(y)       //在类外实现成员函数时在类名后要加<T>
{
};

template <class T>
T Person<T>::XMax()
{
return a > b ? a : b;
};

main()
{
int a = 3, b = 4;
float x = 9.99, y = 10.001;
cout<<mymax(a,b)<<endl;
cout<<mymax(x,y)<<endl;

Person<int> mm;
mm.a = a;
mm.b = b;
cout<<mm.a<<endl;

cout<<endl;

Person<int> gg(3,4);
Person<float> dd(3.3,4.4);
cout<<gg.XMax()<<endl;
cout<<dd.XMax()<<endl;

system("pause");
}

输出:

4
10.001
3

4
4.4
请按任意键继续. . .

posted on 2013-06-11 01:16  ximenchuixie  阅读(193)  评论(0编辑  收藏  举报