chapter11test4

来源:互联网 发布:程序员职业规划 编辑:程序博客网 时间:2024/05/18 10:01

time.h

#ifndef TIME_H_
#define TIME_H_
#include<iostream>
class Time
{
private:
int hour;
int minutes;
public:
Time(int h = 0, int m = 0);
void addh(int h);
void addm(int m);
void reset(int h = 0, int m = 0);
friend Time operator+(const Time &t1, const Time &t2);
friend Time operator-(const Time &t1, const Time &t2);
friend Time operator*(const Time &t1, double n);
friend std::ostream &operator<<(std::ostream &os, const Time &t);
};


#endif


time.cpp

#include<iostream>
#include"time.h"
Time::Time(int h, int m)
{
hour = h; minutes = m;
}
void Time::addh(int h)
{
hour += h;
}
void Time::addm(int m)
{
minutes = (minutes + m) % 60;
hour = hour+(minutes + m) / 60;
}
void Time::reset(int h, int m)
{
hour = h; minutes = m;
}
Time operator+(const Time &t1, const Time &t2)
{
Time t;
t.minutes = (t1.minutes + t2.minutes) % 60;
t.hour = t1.hour + t2.hour + (t1.minutes + t2.minutes) / 60;
return t;
}
Time operator-(const Time &t1, const Time &t2)
{
Time t;
long int tot1 = 60 * t1.hour + t1.minutes; 
long int tot2 = 60 * t2.hour + t2.minutes; 
if (tot1 < tot2)
std::cout << "First time is too little.\n";
else
{
tot1 = tot1 - tot2;
t.hour = tot1 / 60;
t.minutes = tot1 % 60;
}
return t;      //if tot1<tot2,return t(0,0);
}
Time operator*(const Time &t1, double n)
{
Time t; long tot = t1.hour * 60 + t1.minutes;
tot = tot*n;
t.minutes = int(tot) % 60;
t.hour = int(tot) / 60;
return t;
}
std::ostream &operator<<(std::ostream &os, const Time &t)
{
os << "Hour= " << t.hour << " ;Minutes= " << t.minutes << std::endl;
return os;
}


user.cpp

#include<iostream>
#include"time.h"
int main()
{
using namespace std;
Time one(3, 35);
Time two(1, 21);
cout << "Show temp#1=plus :" << one+two<< endl;
cout << "Show temp#2=minus :" << one-two << endl;
cout << "Show temp#3=multi :" << one*0.5 << endl;
two.reset(4, 3);
cout << "Show one and two :" << one << " ; "<<two << endl;
cout << "Show temp#4=minus :" << one - two << endl;
one.addh(3);
cout << "Show temp#5=minus :" << one - two << endl;
return 0;
}

0 0
原创粉丝点击