2.2 函数的重载到模板的重载(例子)

原理链接:C++ 多态 重载 覆盖 2.1 

1 函数重载

1.1头文件

#ifndef _TIME_
#define _TIME_

class Time
{
private:
	int hours;
	int minutes;
public:	
	Time();
	Time(int h, int m);
	Time Add( Time &t1,  Time &t2);
	void show(const Time &t);


};

#endif

 

1.2 实现

#include "time.h"
#include <iostream>
using namespace std;

Time::Time(int h, int m)
{
	hours = h;
	minutes = m;
}
Time::Time()
{
	hours = minutes = 0;
}
Time Time::Add(Time &t1, Time &t2)
{
 Time toatal;
 toatal.minutes = (t1.minutes + t2.minutes)%60;
 toatal.hours = (t1.hours +t2.hours)+(t1.minutes + t2.minutes)/60;
 return toatal;
}

void Time::show(const Time &t3)
{
	cout<<"小时:"<<t3.hours<<endl;
	cout<<"分钟::"<<t3.minutes<<endl;
}

 

1.3 main方法 

#include "time.h"
#include <iostream>
using namespace std;

int main()
{
	Time t1,t;
	Time time1(3,3);
	Time time2(5,90);

	
	t = t1.Add(time1,time2);
	t1.show(t);
	system("pause");
	return 0;
}


2 模板重载

2.1头文件

#ifndef _TIME_
#define _TIME

class Time
{
private:
	int hourse;
	int minutes;
public:
	Time();
	Time(int h, int m);
	Time operator+(const Time &time);
	Time operator-(const Time &time);
	void show(const Time &time) const;
	
};

#endif


 

2.2方法实现

#include "time.h"
#include <iostream>
using namespace std;
 
Time::Time()
{
	hourse = minutes =0;
}
Time::Time(int h, int m)
{
	hourse = h;
	minutes = m;
}
Time Time::operator+(const Time &time)
{
	Time t;
	t.hourse = (time.hourse+hourse)+(time.minutes+minutes)/60;
	t.minutes = (minutes+time.minutes)%60;
	return t;
}
Time Time::operator-(const Time &time)
{
	Time sub;
	Time sub1,sub2;
	sub2.minutes = time.minutes+time.hourse*60;
	/*cout<<"sub2.minutes"<<sub2.minutes<<endl;*/
	sub1.minutes = minutes+hourse*60; 
	/*cout<<"sub2.minutes"<<sub1.minutes<<endl;*/

	sub.minutes = (sub1.minutes-sub2.minutes)%60;
	sub.hourse = (sub1.minutes-sub2.minutes)/60;

	return sub;
}

void Time::show(const Time &tme) const
{
	cout<<"小时:"<<tme.hourse<<"hours"<<endl;
	cout<<"分钟:"<<tme.minutes<<"minutes"<<endl;
}


 

2.3main方法

#include "time.h"
#include <iostream>
using namespace std;

int main()
{
	Time t1(4,35);
	Time t2(2,80);

	Time t,showt;
	t= t1+t2;
	showt.show(t);
	t = t1-t2;
	showt.show(t);
	system("pause");
	return 0;

}


注:以上代码都在VS2010 上可正常运行!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值