设计一个时间类Time,包括时、分、秒等私有数据成员。要求实现时间的基本运算,如一时间加上另一时间(要求:通过成员函数重载+运算符实现)、一时间减去另一时间(要求:通过普通函数重载-运算符实现)等,编写主函数调用。
time.h
#ifndef TIME_H
#define TIME_H
class Time
{
int hour;
int minute;
int second;
public:
Time(int h=0,int m=0,int s=0);
friend Time operator+(const Time&t1,const Time&t2);
friend Time operator-(const Time&t1,const Time&t2);
void showInfo();
};
#endif // TIME_H
time.cpp
#include "time.h"
#include<iostream>
using namespace std;
Time::Time(int h,int m,int s):hour(h),minute(m),second(s)
{
}
Time operator+(const Time&t1,const Time&t2)
{
int h=t1.hour+t2.hour;
int m=t1.minute+t2.minute;
int s=t1.second+t2.second;
if(s>=60)
{
s=s-60;
m=m+1;
}
if(m>=60)
{
m=m-60;
h=h+1;
}
return Time(h,m,s);
}
Time operator-(const Time&t1,const Time&t2)
{
int h=t1.hour-t2.hour;
int m=t1.minute-t2.minute;
int s=t1.second-t2.second;
if(s<0)
{
s=s+60;
m=m-1;
}
if(m<0)
{
m=m+60;
h=h-1;
}
return Time(h,m,s);
}
void Time::showInfo()
{
cout<<hour<<":"<<minute<<":"<<second<<endl;
}
main.cpp
#include <iostream>
#include"time.h"
using namespace std;
int main()
{
Time t1(8,40,50),t2(4,2,34);
cout<<"t1=";
t1.showInfo();
cout<<"t2=";
t2.showInfo();
Time t3;
t3=t1+t2;
cout<<"t1+2=";
t3.showInfo();
t3=t1-t2;
cout<<"t1-t2=";
t3.showInfo();
return 0;
}
最后就可以根据t1和t2计算出t1+t2的值、t1-t2的值。