设计一个时间类CTime
包括时、分、秒等私有数据成员。要求实现时间的基本运算,如一时间加上另一时间、一时间减去另一时间等。
参考程序:
#include <iostream>
using namespace std;
class CTime
{
int hour; //时数
int minute; //分数
int second; //秒数
public:
CTime() {} //默认构造函数
CTime(int h =0,int m =0,int s=0):hour(h),minute(m),second(s){}// 重载构造函数
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;
}
CTime operator+(CTime);
CTime operator-(CTime);
void disp();
};
CTime CTime::operator +(CTime t)
{
int carry,hh,mm,ss;
ss=getsecond()+t.getsecond();
if (ss>60) {
ss-=60;
carry=1; //秒数大于60,则需进一位
}
else
carry=0;
mm=getminute()+t.getminute()+carry;
if (mm>60) {
mm-=60;
carry=1; //分数大于60,则需进一位
}
else
carry=0;
hh=gethour()+t.gethour()+carry;
if (hh>24)
hh-=24;
static CTime result(hh,mm,ss); // 构造一个静态对象result
return result;
}
CTime CTime::operator -(CTime t) {
int borrow,hh,mm,ss;
ss=getsecond()-t.getsecond();
if (ss<0) {
ss+=60;
borrow=1; // 秒数小于0,则需从分数借一位
}
else
borrow=1;
mm=getminute()-t.getminute()-borrow;
if (mm<0) {
mm+=60;
borrow=1; // 分数小于0,则需从分数借一位
}
else
borrow=0;
hh=gethour()-t.gethour()-borrow;
if (hh<0)
hh+=24;
static CTime result(hh,mm,ss);
return result;
}
void CTime::disp() {
cout << hour << ":" << minute << ":" << second << endl;
}
int main(void)
{
CTime now(8,50,40);
CTime start(24,55);
CTime t1=now-start;
CTime t2=now+start;
cout << "time 1:";
now.disp();
cout << "time 2:";
start.disp();
cout << "time plus: ";
t1.disp();
cout << "time add: ";
t2.disp();
return 0;
}
测试结果
关于Image Engineering& Computer Vision更多讨论与交流,敬请关注本博客和新浪微博songzi_tea.