C++---使用类

本文介绍了一个Time类的设计,该类通过运算符重载实现了时间的加法、减法和乘法操作。通过具体的代码示例,展示了如何在C++中使用运算符重载来增强类的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

运算符重载

实现一个Time类,重载加法、减法和乘法运算符:

1.头文件:

//mytime.h--Time class with operator overloading
#ifndef MYTIME_H_
#define MYTIME_H_
class Time
{
private:
    int hours;
    int minutes;
public:
    Time();
    Time(int hour, int minute = 0);
    void AddMinute(int minute);
    void AddHour(int hour);
    void Reset(int hour = 0, int minute = 0);
    Time operator+(const Time &t) const;
    Time operator-(const Time &t) const;
    Time operator*(double mult) const;
    void show() const;
};
#endif // MYTIME_H_

2.源文件:

//mytime.cpp --implementing Time methods
#include <iostream>
#include "mytime.h"
using namespace std;
Time::Time()
{
    hours = minutes = 0;
}
Time::Time(int hour, int minute)
{
    this->hours = hour;
    this->minutes = minute;
}
void Time::AddMinute(int minute)
{
    this->minutes += minute;
    this->hours += minutes / 60;
    this->minutes = minutes % 60;
}
void Time::AddHour(int hour)
{
    this->hours += hour;
}
void Time::Reset(int hour, int minute)
{
    this->hours = hour;
    this->minutes = minute;
}
Time Time::operator+(const Time &t) const
{
    Time sum;
    sum.minutes = this->minutes + t.minutes;
    sum.hours = this->hours + t.hours + sum.minutes / 60;
    sum.minutes %= 60;
    return sum;
}
Time Time::operator-(const Time &t) const
{
    Time diff;
    int tot1, tot2;
    tot1 = this->minutes+ 60 * this->hours;
    tot2 = t.minutes + 60 * t.hours;
    diff.minutes = (tot1 - tot2) % 60;
    diff.hours = (tot1 - tot2) / 60;
    return diff;
}
Time Time::operator*(double mult) const
{
    Time result;
    long totalminutes = hours * mult * 60 + minutes * mult;
    result.minutes = totalminutes % 60;
    result.hours = totalminutes / 60;
    return result;
}
void Time::show() const
{
    cout << hours << " hours, " << minutes << " minutes" << endl;
}

3.客户文件:

//usemytime.cpp
#include <iostream>
#include "mytime.h"
using namespace std;

int main()
{
    Time weeding(4, 35);
    Time waxing(2, 47);
    Time total;
    Time diff;
    Time adjusted;

    cout << "weeding time = ";
    weeding.show();

    cout << "waxing time = ";
    waxing.show();

    cout << "total work time = ";
    total = weeding + waxing; //use operator+()
    total.show();

    cout << "diff work time = ";
    diff = weeding - waxing; //use operator-()
    diff.show();

    cout << "adjusted work time = ";
    adjusted = total * 1.5; //use operator*()
    adjusted.show();

    return 0;
}

运行结果:

weeding time = 4 hours, 35 minutes
waxing time = 2 hours, 47 minutes
total work time = 7 hours, 22 minutes
diff work time = 1 hours, 48 minutes
adjusted work time = 11 hours, 3 minutes

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值