1函数模板
#include<iostream>
using namespace std;
template <typename T>
T max(T a,T b,T c)
{
if(a<b)a=b;
if(a<c)a=c;
return a;
}
int main()
{
int i;float f;double d;
int i1=44,i2=33, i3=55;
float f1=324.1, f2=12.324, f3=454.1;
double d1=1.23234, d2=3.32423, d3=35.234;
i=max(i1,i2,i3);
f=max(f1,f2,f3);
d=max(d1,d2,d3);
cout<<i<<" "<<f<<" "<<d<<endl;
return 0;
}
2类模板(类内定义方法)
#include<iostream>
using namespace std;
template<class T>
class compare
{
public:
compare(T a,T b)
{
h=a;
w=b;
}
T min()
{
return(h>w)?w:h;
}
T max()
{
return(h>w)?h:w;
}
private:
T h;
T w;
};
int main()
{ int i;float f;
compare<int> c1(3,6);
i=c1.min();
cout<<i<<endl;
i=c1.max();
cout<<i<<endl;
compare<float> c2(4.31,65.1);
f=c2.min();
cout<<f<<endl;
f=c2.max();
cout<<f<<endl;
return 0;
}
2类模板(类外定义方法)
#include<iostream>
using namespace std;
template<class T>
class compare
{
public:
compare(T a,T b);
T min();
T max();
private:
T h;
T w;
};
template<class T>
compare<T>::compare(T a,T b)
{
h=a;
w=b;
}
template<class T>
T compare<T>::min()
{
if(h<w)
return h;
return w;
}
template<class T>
T compare<T>::max()
{
if(h<w)
return w;
return h;
}
int main()
{ int i;float f;
compare<int> c1(3,6);
i=c1.min();
cout<<i<<endl;
i=c1.max();
cout<<i<<endl;
compare<float> c2(4.31,65.1);
f=c2.min();
cout<<f<<endl;
f=c2.max();
cout<<f<<endl;
return 0;
}