定制一个类模板,然后覆盖类模板中所定义的所有成员
#include <iostream>
using namespace std;
class Date
{
int iMonth,iDay,iYear;
char Format[128];
public:
Date(int m = 0,int d = 0,int y = 0)
{
iMonth = m;
iDay = d;
iYear = y;
}
friend ostream& operator<<(ostream& os,const Date t)
{
cout << "Month:" << t.iMonth << ' ';
cout << "Day:" << t.iDay << ' ';
cout << "Year:" << t.iYear << ' ';
return os;
}
void Display()
{
cout << "Month:" << iMonth << ' ';
cout << "Day:" << iDay << ' ';
cout << "Year:" << iYear << endl;
}
};
template<class T>
class Set
{
T t;
public:
Set(T st):t(st) { }
void Display()
{
cout << "t:" << t << endl;
}
};
template<>
class Set<Date>
{
Date t;
public:
Set(Date st):t(st) {}
void Display()
{
cout << "Date:" << t << endl;
}
};
int main()
{
Set<int> intset(123);
Set<Date> dt = Date(1,2,3);
intset.Display();
dt.Display();
return 0;
}
运行结果
程序中定义了Set类模板,该类模板中有一个构造函数和一个Display 成员函数。Display 成员函数负责输出成员的值。
使用类Date定制了整个类模板,也就是说模板类中 构造函数中的参数是Date对象,Display成员函数输出的 也是Date对象。
定制类模板相当于实例化一个模板类。