运算符重载
实现一个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