C++程序设计(PEARSON版)第三版9.5答案C++代码

*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;  
 } 

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值