一、模板简单应用(比较大小)
#include<iostream>
using namespace std;
template<typename Type>
Type maax(Type num_first,Type num_secend)
{
Type maxNum = (num_first > num_secend)?num_first:num_secend;
return maxNum;
}
int main()
{
int bb=max(4,6);
cout<<bb<<endl;
cout<<maax(4,6)<<endl;
cout<<maax(7.7,9.9)<<endl;
return 0;
}
#include<iostream>
using namespace std;
template<typename T1, typename T2, typename T3>
T3 maxx(T1 num1, T2 num2)
{
T3 num=(num1>num2)?num1:num2
return num;
}
int main()
{
cout<<maxx(6, 7.7)<<endl;
return 0;
}
#include<iostream>
using namespace std;
template<typename T1, typename T2>
T2 maxx(T1 num1, T2 num2)
{
T2 num=(num1>num2)?num1:num2;
return num;
}
int main()
{
cout<<maxx(6, 7.7)<<endl;
return 0;
}
二、类中包含模板
#include<iostream>
using namespace std;
template<typename T1, typename T2>
class class_max
{
public:
class_max(T1 x1,T2 X2 );
void show();
private:
T1 num1;
T2 num2;
};
template<typename T1, typename T2>
class_max<T1, T2>::class_max(T1 x1,T2 x2) : num1(x1), num2(x2)
{
}
template<typename T1, typename T2>
void class_max<T1, T2>::show()
{
T1 tempNum;
tempNum=(num1>num2)?num1:num2;
cout<<"max num is:"<<tempNum<<endl;
}
int main()
{
class_max<int,int> max1(6, 8);
max1.show();
class_max<float, float> max2(6.7,8.8);
max2.show();
class_max<float, int> max3(9.9, 5);
max3.show();
return 0;
}