编写一个程序,定义一个时间类Time

编写一个程序,定义一个时间类Time,包含三个私有成员变量: hour, minute 和 second。
成员函数包括:
1、定义带三个参数的构造函数,每个参数设置默认值为0,在函数内部判断传递实参值如果不在合法范围,也就是小时不在0~23之间,分钟和秒不在0~59之间,那就将当前值赋值为默认值0.
2、定义并实现该类的复制构造函数。

3、定义并实现print()函数输出时间。
4、定义并实现increment()函数,将当前时间减少1秒。
5、定义并实现decrement()函数,将当前时间增加1秒。

回答:

#include<iostream>

using namespace std;

class Time{

 private:

 int hour,minute,second;

 public:

 Time(int h=0,int m=0,int s=0);

 Time(const Time &a){

  hour=a.hour;

  minute=a.minute;

  second=a.second;}

 void print();

 void increment();

    void decrement(); 

};

int main(){

 Time time1; 

 Time time2(time1);

 time1. print();

 time1. decrement();

    time1. print();  

 time2.print();

 time2.increment();

 time2.print();

 return 0;

}

void Time::print(){

 cout<<hour<<":"<<minute<<":"<<second<<endl;

}

void Time::increment(){

  if (second>0)

{

 second--;

}

 else if(second==0){

 if (minute>0)

 {

 second=59;

 minute--;

}

 else if(minute==0){

 if (hour>0)

 {

 minute=59;

 second=59;

 hour--;

 }

 else if(hour==0){

 minute=59;

  second=59;

 hour=23;

 } 

 } 

 

void Time::decrement(){

if (second<59)

 {

 second++;

}

 else if(second==59){

 if (minute<59)

{

 second=0;

 minute++;

 }

 else if(minute==59){

 if (hour<23)

 {

 minute=0;

 second=0;

 hour++;

 }

 else if(hour==23){

 minute=0;

 second=0;

 hour=0;

 } 

 } 

 } 

}

 Time::Time(int h,int m,int s){

 cin>>h>>m>>s;

 hour=h;minute=m;second=s;

 if(hour<0||hour>23)hour=0;

    if(minute<0||minute>59)minute=0;

    if(second<0||second>59)second=0;

  }

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学习令我充实

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值