定制类模板的一个简单实例

定制一个类模板,然后覆盖类模板中所定义的所有成员

#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对象。

定制类模板相当于实例化一个模板类。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

瑟寒凌风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值