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();


}

 

 


发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注