prog9.cpp
来自「C++语言程序设计题典」· C++ 代码 · 共 89 行
CPP
89 行
#include <iostream.h>
class Time
{
int hour,minute,second;
public:
Time() {};
Time(int h,int m,int s)
{
hour=h;minute=m;second=s;
}
Time(int h,int m)
{
hour=h;minute=m;second=0;
}
Time(int h)
{
hour=h;minute=0;second=0;
}
void sethour(int h) { hour=h; }
void setminute(int m) { minute=m; }
void setsecond(int s) { second=s; }
int gethour() { return hour; }
int getminute() { return minute; }
int getsecond() { return second; }
Time operator+(Time);
Time operator-(Time);
void disp()
{
cout << hour << ":" << minute << ":" << second << endl;
}
};
Time Time::operator +(Time t)
{
int carry,hh,mm,ss;
ss=getsecond()+t.getsecond();
if (ss>60)
{
ss-=60;
carry=1; //进位标记
}
else carry=0;
mm=getminute()+t.getminute()+carry;
if (mm>60)
{
mm-=60;
carry=1;
}
else carry=0;
hh=gethour()+t.gethour()+carry;
if (hh>24)
hh-=24;
static Time result(hh,mm,ss);
return result;
}
Time Time::operator -(Time t)
{
int borrow,hh,mm,ss;
ss=getsecond()-t.getsecond();
if (ss<0)
{
ss+=60;
borrow=1; //借位标记
}
else borrow=1;
mm=getminute()-t.getminute()-borrow;
if (mm<0)
{
mm+=60;
borrow=1;
}
else borrow=0;
hh=gethour()-t.gethour()-borrow;
if (hh<0)
hh+=24;
static Time result(hh,mm,ss);
return result;
}
void main()
{
Time now(2,24,39);
Time start(17,55);
Time t1=now-start,t2=now+start;
cout << "输出结果:" << endl;
cout << " now: ";now.disp();
cout << " start:";start.disp();
cout << " 相差: ";t1.disp();
cout << " 相加: ";t2.disp();
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?