【问题描述】对前面实验写过的Time类进行修改,删去Add和Sub成员函数,通过重载“+”、“-”运算符直接进行时间的加减运算。
提示:
(1)可以用友元函数来实现“+”“-”运算符的重载。
(2)加法运算符可以是两个Time对象进行相加,也可以是一个表示秒数的int型数据加上一个Time对象,还可以是Time对象加上int型数据,得到的结果都是Time类型的对象。
(3)减法运算符可以是两个Time对象进行相减,也可以是Time对象减去一个表示秒数的int型数据,得到的结果都是Time类型的对象。
主函数设计如下,请勿修改:
int main(){
Time t1(2,34),t2,t3;
t2.SetTime(13,23,34);
cout<<"t1+t2:";
t3=t1+t2;//两个Time类对象相加
t3.print_24();
cout<<"\nt1+65:";
t3=t1+65;//Time类对象加上65秒
t3.print_24();
cout<<"\n65+t1:";
t3=65+t1;//65秒加上Time类对象
t3.print_24();
cout<<"\nt2-t1:";
t3=t2-t1;//两个Time类对象相减
t3.print_24();
cout<<"\nt1-70:";
t3=t1-70;//Time类对象减去70秒
t3.print_24();
return 0;
}
【样例输出】
t1+t2:15:57:34
t1+65:02:35:05
65+t1:02:35:05
t2-t1:10:49:34
t1-70:02:32:50
///Time类
#include<iostream>
using namespace std;
#include<stdio.h>
#include<cmath>
class Time{
int hour,minute,second;
public:
Time(int h,int m,int s=0);
Time(int s=0);
int SecCalc(){return(hour*60+minute)*60+second;
}
void SetTime(int h=0,int m=0,int s=0);
void print_12();
void print_24();
Time operator+(Time b)
{
Time kk(0,0,0);
int result=b.SecCalc()+SecCalc();
kk.hour=(result/3600)%24;
result%=3600;
kk.minute=(result/60);
kk.second=result%60;
return kk;
}
Time operator-(Time b)
{
Time kk(0,0,0);
int result=fabs(b.SecCalc()-SecCalc());
kk.hour=(result/3600)%24;
result%=3600;
kk.minute=(result/60);
kk.second=result%60;
return kk;
}
Time operator+(int b)
{
Time kk(0,0,0);
int result=b+SecCalc();
kk.hour=(result/3600)%24;
result%=3600;
kk.minute=(result/60);
kk.second=result%60;
return kk;
}
Time operator-(int b)
{
Time kk(0,0,0);
int result=fabs(SecCalc()-b);
kk.hour=(result/3600)%24;
result%=3600;
kk.minute=(result/60);
kk.second=result%60;
return kk;
}
friend Time operator+(int,Time);
};
Time operator+(int b,Time r)
{
Time kk(0,0,0);
int result=b+r.SecCalc();
kk.hour=(result/3600)%24;
result%=3600;
kk.minute=(result/60);
kk.second=result%60;
return kk;
}
Time::Time(int h,int m,int s)
{
hour=h;
minute=m;
second=s;
}
void Time::SetTime(int hh,int mm,int ss)
{
hour=hh;
minute=mm;
second=ss;
}
Time::Time(int s)比之前的要简单些
{
hour=(s/3600)%24;
s%=3600;
minute=s/60;
second=s%60;
}
void Time::print_12()
{
int h=hour;
h%=12;
printf("%02d:%02d:%02d",h,minute,second);
if(hour>=12) cout<<" PM";
else cout<<" AM";
cout<<endl;
}
void Time::print_24()
{
printf("%02d:%02d:%02d",hour,minute,second);
cout<<endl;
}
int main(){
Time t1(2,34),t2,t3;
t2.SetTime(13,23,34);
cout<<"t1+t2:";
t3=t1+t2;//两个Time类对象相加
t3.print_24();
cout<<"\nt1+65:";
t3=t1+65;//Time类对象加上65秒
t3.print_24();
cout<<"\n65+t1:";
t3=65+t1;//65秒加上Time类对象
t3.print_24();
cout<<"\nt2-t1:";
t3=t2-t1;//两个Time类对象相减
t3.print_24();
cout<<"\nt1-70:";
t3=t1-70;//Time类对象减去70秒
t3.print_24();
return 0;
}