Demo entry 6364841

c++

   

Submitted by anonymous on May 17, 2017 at 08:34
Language: C++. Code size: 1.6 kB.

#include<iostream>
using namespace std;
class Time{
public:
    Time(){};//构造函数
    Time(int h,int m,int s){//构造函数
        this->h=h;
        this->m=m;
        this->s=s;
    }
    void setTime(int h,int m,int s){//输入函数
        this->h=h;
        this->m=m;
        this->s=s;
    }
    void showTime(){//输出函数
        cout<<h<<"小时"<<m<<"分"<<s<<"秒"<<endl;
    }
    Time operator+(Time t);//加法
    Time operator-(Time t);//减法
private:
    int h;//时
    int m;//分
    int s;//秒
};
Time Time::operator+(Time t){//加法实现
        int s=this->s;
        int m=this->m;
        int h=this->h;


        s=s+t.s;
        if(s>=60){//秒过60时,分钟要进一
            m++;
            s=s-60;
        }
        m=m+t.m;
        if(m>=60){//分钟过60时,小时要进一
            h++;
            m=m-60;
        }
        h=h+t.h;
        return Time(h,m,s);
}
Time Time::operator-(Time t){//减法实现
        int s=this->s;
        int m=this->m;
        int h=this->h;

        s=s-t.s;
        if(s<0){//秒小于0时,分钟要减一
            m--;
            s=60+s;//秒要与借位来的60运算
        }
        m=m-t.m;
        if(m<0){
            h--;
            m=60+m;//分钟要与借位来的60运算
        }
        h=h-t.h;
        return Time(h,m,s);
}
int main(){
    Time t1,t2,t3;
    t1.setTime(15,12,46);//测试数据t1
    cout<<"t1=";
    t1.showTime();

    t2.setTime(6,13,25);//测试数据t2
    cout<<"t2=";
    t2.showTime();

    t3=t1+t2;
    cout<<"t1+t2=";
    t3.showTime();//t1+t2不会改变t1的值了,将t1的运算符重载函数改一下

    t3=t1-t2;
    cout<<"t1-t2=";
    t3.showTime();
    return 0;
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).