list.h
# pragma once
# ifndef list_H_
# define list_H_
#include <iostream>
class Time {
private:
int hours;
int minutes;
public:
Time();
Time(int h, int m);
void AddMin(int m);
void AddHt(int h);
void Reset(int h, int m);
Time operator *(double m)const;
friend const Time operator +(const Time & t, const Time & s);//重载加法
friend const Time operator -(const Time & t, const Time & s);//重载减法
friend const Time operator *(double m, const Time & t)
{
return t*m;
}//重载乘法
friend std::ostream & operator <<(std::ostream & os, const Time & t);
};
# endif
function.cpp
#include "list.h"
Time::Time()
{
hours = minutes = 0;
}
Time::Time(int h, int m)
{
hours = h;
minutes = m;
}
void Time::AddMin(int m)
{
minutes += m;
hours += minutes / 60;
minutes %= m;
}
void Time::AddHt(int h)
{
hours += h;
}
void Time::Reset(int h, int m)
{
hours = h;
minutes = m;
}
const Time operator+(const Time & t, const Time & s)
{
Time sum;
sum.minutes = s.minutes + t.minutes;
sum.hours = s.hours + t.hours + sum.minutes / 60;
sum.minutes %= 60;
return sum;
}
const Time operator-(const Time & t, const Time & s)
{
Time diff;
int tot2, tot1;
tot1 = t.minutes + 60 * t.hours;
tot2 = s.minutes + 60 * s.hours;
diff.minutes = (tot1 - tot2)%60;
diff.hours = (tot1 - tot2) / 60;
return diff;
}
Time Time:: operator*(double m)const
{
Time result;
long totalminutes = hours*m * 60 + minutes*m;
result.hours = totalminutes / 60;
result.minutes = totalminutes % 60;
return result;
}
std::ostream & operator<<(std::ostream & os, const Time & t)
{
os << t.hours << " hours " << t.minutes << " minutes ";
return os;
}
main.cpp
#include "list.h"
#include <iostream>
#include <cstdlib>
int main()
{
using std::cout;
using std::endl;
Time aida(3, 35);
Time tosca(2, 48);
Time temp;
cout << "Aida and Tosca:\n";
cout << aida << "; " << tosca << endl;
temp = aida + tosca;
cout << "Aida + Tosca: " << temp << endl;
temp = aida*1.17;
cout << "Aida * 1.17: " << temp << endl;
cout << "10 * Tosca: " << 10.0*tosca << endl;
system("pause");
return 0;
}