//一个表示时间的Time类 (精确到分钟)
#include <iostream>
using namespace std;
class Time
{
private:
int hours;
int minutes;
public:
Time();
Time(int h, int m = 0);
void AddMin(int m);
void AddHr(int h);
void Reset(int h = 0, int m = 0);
int toMin() { return minutes + hours * 60; };
Time operator+(const Time& t) const;
Time operator-(Time& t);
Time operator*(Time &t);
void Show() const;
friend ostream& operator<<(ostream& om, const Time& t);
};
Time::Time()
{
hours = minutes = 0;
}
Time::Time(int h, int m)
{
if (h < 0)
{
cout << "Are you kidding me??" << endl;
hours = 0;
}
else
{
hours = h;
}
if(m<0)
{
cout << "Are you kidding me??"<<endl;
minutes = 0;
}
else
{
minutes = m;
}
hours += minutes / 60;
minutes %= 60;
}
void Time::AddMin(int m)
{
minutes += m;
hours += minutes / 60;
minutes %= 60;
}
void Time::AddHr(int h)
{
hours += h;
}
void Time::Reset(int h, int m)
{
hours = h;
minutes = m;
}
Time Time::operator+(const Time& t)const
{
Time sum;
sum.hours = hours;
sum.minutes = minutes;
sum.AddHr(t.hours);
sum.AddMin(t.minutes);
return sum;
}
Time Time::operator-(Time& t)
{
int tem_minutes = toMin() - t.toMin();
if (tem_minutes < 0)
{
cout << "Are you kidding me??" << endl;
Time dvalue;
return dvalue;
}
else
{
Time dvalue(0, tem_minutes);
return dvalue;
}
}
Time Time::operator*(Time& t)
{
int tem_minutes = toMin()*t.toMin();
Time result(0,tem_minutes);
return result;
}
void Time::Show()const
{
cout << hours << "hours," << minutes << "minutes";
}
ostream& operator<<(ostream& om, const Time& t)
{
om << t.hours << "hours," << t.minutes << "minutes";
return om;
}
int main()
{
Time t1(4, 30);//调用有参数的构造函数。
Time t2(5, 70);
(t1 + t2).Show(); //等价于 t1.operator+(t2).Show();
Time t3(5, 300);
cout << endl;
t3.Show();
cout << endl;
cout << (t1 + t2 + t3) << endl;
// 这里首先运算括号里的表达式,
//t1+t2先被执行,返回一个临时的Time对象,这个对象再调用
//operator+()函数,返回存储了最终运算结果的临时的Time对象
//最后调用operator<<()友元函数。
Time t4;
cout << t4 << endl;
cout << (t3 - t2)<<endl;
cout << (t2 * t3);
}
一个简单的表示时间的类 C++实现
最新推荐文章于 2024-04-04 11:49:38 发布