*9.5设计一个名为Time的类,类包含:
- 数据域hour,minute,second,为当前时间创建一个Time对象
- 一个无参构造函数,为当前时间创建一个Time对象。
- 一个构造函数,按给出的自1970年1月1日0时流逝的秒数所指出的时间,创造一个Time对象。
- 一个构造函数,创建一个给定hour,minute,和second的Time对象
- 数据域hour,minute,second的3个get函数。
- 一个成员函数setTime(int espaceTime),使用流逝的秒数为对象设置新的时间。
- 编写一个测试程序,他创建两个Time对象(分别使用Time()和Time(555550)),然后输出他们的小时,分,秒
- 使用下方代码注意修改头文件名,本代码在Dev-C++编译器上获得通过
类的头文件代码如下:
#ifndef TIME2_H
#define TIME2_H
class Time
{
public:
Time();
Time(int);
Time(int,int,int);
int getSec();
int getMin();
int getHour();
void setTime(int elapseTime);
private:
int sec;
int min;
int hour;
public:
int totalsecs;
int totalmins;
int totalhours;
};
#endif
类的函数实现代码
#include<iostream>
#include"Time2.h"
#include<ctime>
//using namespace std;
Time::Time()
{
totalsecs=time(0);
setTime(totalsecs);
}
Time::Time(int a)
{
totalsecs=a;
setTime(a);
}
Time::Time(int ksec,int kmin,int khour)
{
sec=ksec;
min=kmin;
hour=khour;
}
int Time::getSec()
{
return sec;
}
int Time::getMin()
{
return min;
}
int Time::getHour()
{
return hour;
}
void Time::setTime(int elapseTime)
{
totalsecs=elapseTime;
sec=totalsecs%60;
totalmins=totalsecs/60;
min=totalmins%60;
totalhours=totalmins/60;
hour=totalhours%24;
}
主函数代码:
#include<iostream>
#include"Time2.h"
#include"Time3.cpp"
//#include<ctime>
using namespace std;
int main()
{
Time time1;
cout<<"当前秒数:"<<time1.getSec()<<endl;
cout<<"当前分钟数:"<<time1.getMin()<<endl;
cout<<"当前小时数:"<<time1.getHour()<<endl;
Time time2(555550);
cout<<"指定时间秒数:"<<time2.getSec()<<endl;
cout<<"指定时间分钟数:"<<time2.getMin()<<endl;
cout<<"指定时间小时数:"<<time2.getHour()<<endl;
return 0;
}