Qt C++面向对象程序设计 友元、重载的运用 实现时间的基本运算

本文介绍了如何在C++中设计一个包含时、分、秒的Time类,通过重载+和-运算符实现时间的相加和相减功能,并在主函数中展示了实例操作。
摘要由CSDN通过智能技术生成

 设计一个时间类Time,包括时、分、秒等私有数据成员。要求实现时间的基本运算,如一时间加上另一时间(要求:通过成员函数重载+运算符实现)、一时间减去另一时间(要求:通过普通函数重载-运算符实现)等,编写主函数调用。

time.h

#ifndef TIME_H
#define TIME_H

class Time
{
    int hour;
    int minute;
    int second;
public:
    Time(int h=0,int m=0,int s=0);
    friend Time operator+(const Time&t1,const Time&t2);
    friend Time operator-(const Time&t1,const Time&t2);
    void showInfo();

};

#endif // TIME_H

time.cpp

#include "time.h"
#include<iostream>
using namespace std;
Time::Time(int h,int m,int s):hour(h),minute(m),second(s)
{
}
Time operator+(const Time&t1,const Time&t2)
{
    int h=t1.hour+t2.hour;
    int m=t1.minute+t2.minute;
    int s=t1.second+t2.second;
    if(s>=60)
    {
        s=s-60;
        m=m+1;
    }
    if(m>=60)
    {
        m=m-60;
        h=h+1;
    }
    return Time(h,m,s);
}
Time operator-(const Time&t1,const Time&t2)
{
    int h=t1.hour-t2.hour;
    int m=t1.minute-t2.minute;
    int s=t1.second-t2.second;
    if(s<0)
    {
        s=s+60;
        m=m-1;
    }
    if(m<0)
    {
        m=m+60;
        h=h-1;
    }
    return Time(h,m,s);
}
void Time::showInfo()
{
    cout<<hour<<":"<<minute<<":"<<second<<endl;
}

main.cpp

#include <iostream>
#include"time.h"
using namespace std;

int main()
{
    Time t1(8,40,50),t2(4,2,34);
    cout<<"t1=";
    t1.showInfo();
    cout<<"t2=";
    t2.showInfo();
    Time t3;
    t3=t1+t2;
    cout<<"t1+2=";
    t3.showInfo();
    t3=t1-t2;
    cout<<"t1-t2=";
    t3.showInfo();
    return 0;
}

最后就可以根据t1和t2计算出t1+t2的值、t1-t2的值。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值