C++primer plus第六版课后编程题答案11.4

mytime.h


#ifndef MYTIME_h_
#define MYTIME_h_
#include <iostream>
//为了方便我全部写成inline函数了
class Time
{
private:
	int hours;
	int minutes;
public:
	Time(){
		hours=minutes=0;
	};
	Time(int h,int m=0){
		hours=h;
		minutes=m;
	};
	void Reset(int h=0,int m=0)
	{
		hours=h;
		minutes=m;
	};
	Time operator+(const Time &t)const
	{
		int jinwei=0;
		int newh=hours+t.hours;
		int newm=minutes+t.minutes;
		if(newm>60)
		{
			newm=newm%60;
			jinwei=1;
		}
		newh+=jinwei;
		return Time(newh,newm);
	};

	Time operator+(double m)const//重载+
	{
		int jinwei=0;
		int newm=m+minutes;
		if(newm>60)
		{
			newm=newm%60;
			jinwei=1;
		}
		int newh=hours+jinwei;
		return Time(newh,newm);
	};


	Time operator-(const Time &t)const
	{
		int jinwei=0;
		int newh=hours-t.hours;
		int newm=minutes-t.minutes;
		if(newm<0)
		{
			newm=minutes-t.minutes+60;
			jinwei=-1;
		}
		newh+=jinwei;
		return Time(newh,newm);	
	
	
	};
	Time operator*(double n)const{
		double totalsource=hours*60+minutes;//原来的分钟数
		double totalnow=totalsource*n;
		int newh=totalnow/60;
		int newm=int(totalnow)%60;//求余必须为int
		return Time(newh,newm);
	};
	friend Time operator*(double n,const Time &t){
		return t*n;
	};
	friend Time operator-(const Time &t,double m){
		double total=t.hours*60+t.minutes;
		int now=total-m;
		int newh=now/60;
		int newm=now%60;//求余必须为int
		return Time(newh,newm);
	};
	friend Time operator+(double m,const Time &t)
	{
		return t+m;
		
	}
	friend std::ostream &operator<<(std::ostream &os,const Time &t)
	{
		os<<t.hours<<" hours,"<<t.minutes<<" minutes."<<std::endl;
		return os;
	};

};
#endif

main114.cpp

#include<iostream>
#include"myTime.h"
using namespace std;
void main114()
{
	Time t1;
	Time t2(6,9);
	Time t3(7);
	Time t4(4,59);
	/*构造测试
	cout<<t1<<endl;
	cout<<t2<<endl;
	cout<<t3<<endl;
	*/
	Time t5=t1+t2;
	//cout<<t5<<endl;
	//t5=t2+t4;
	//cout<<t5<<endl;
	//t5=t2+10;
	//cout<<t5<<endl;
	//t5=t4*2;
	t5=t2-t4;
	cout<<t5<<endl;



	cin.get();


}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值