C++第二天作业

本文介绍了如何在C++中创建一个名为`timer`的类,用于表示时间间隔,并实现加法、减法运算以及通过索引访问小时、分钟和秒的方法。示例展示了如何实例化并使用这个类进行时间计算。
摘要由CSDN通过智能技术生成
 #include <iostream>
 using namespace std;
 class timer {
     public:
         timer():sec(0),min(0),hour(0){}
         timer(int sec,int min,int hour){this->sec = sec;this->min = min;this->hour = hour;}
         timer operator+(timer &t)
         {
             timer temp;
             temp.sec = t.sec + this->sec;
             temp.min = t.min + this->min;
             temp.hour = t.hour + this->hour;
             return temp;
         }
         timer operator-(timer &t)
         {
             timer temp;
             temp.sec = t.sec - this->sec;
             temp.min = t.min - this->min;
             temp.hour = t.hour - this->hour;
             return temp;
         }
         timer operator+(int n)
         {
             timer temp;
             temp.sec = this->sec + n;
             return temp;                                                                                   
         }
         int &operator[](int n)
         {
             timer temp;
             if(n == 0)
             {
                 temp.hour = this->hour;
             }
             else if(n == 1)
             {
                 temp.min = this->min;
             }
             else
             {
                 temp.sec = this->sec;
             }
             return temp;
         }
 
             void show()
             {
                 cout<<"hour:"<<this->hour<<" min:"<<this->min<<" sec:"<<this->sec<<endl;
             }
 
     private:
         int sec;
         int min;
         int hour;
 };
int main(int argc, const char *argv[])
{
    timer t1;
    timer t3;
    t3 = t1 + 2;
    t3.show();
    timer t[0];
    t.show();
    return 0;
}

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值