// Java 里有重载,但没有操作符重载。
// 这个是C++ 代码, 明天我会将它移到C++ 教室板块的。
[CODE]
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
class Hours
{
int h;
public:
Hours(){}
Hours(int h){this->h = h;}
int getH(){ return h;}
void reset(){h = 0;}
void operator +=(Hours & h){ this->h += h.h;}
};
class Minutes
{
int m;
public:
Minutes(){}
Minutes(int m){this->m = m;}
int getM(){ return m;}
void reset(){ m = 0;}
void operator +=(Minutes & m){ this->m += m.m;}
};
struct Seconds
{
int s;
public:
Seconds(){}
Seconds(int s){this->s = s;}
int getS(){ return s;}
void reset(){ s = 0;}
void operator +=(Seconds & s){ this->s += s.s;}
};
class Time
{
private:
Hours hours;
Minutes minutes;
Seconds seconds;
void reset()
{
hours.reset();
minutes.reset();
seconds.reset();
}
public:
Time(Hours h = 0, Minutes m = 0, Seconds s = 0)
{
hours = h;
minutes = m;
seconds = s;
}
Time(Hours h)
{
Time(h, 0, 0);
}
Time(Minutes m)
{
Time(0, m, 0);
}
Time(Seconds s)
{
Time(0, 0, s);
}
Time(Hours h, Minutes m)
{
Time(h, m, 0);
}
Time(Hours h, Seconds s)
{
Time(h, 0, s);
}
Time(Minutes m, Seconds s)
{
Time(0, m, s);
}
Time(Time & t)
{
this->hours = t.hours;
this->minutes = t.minutes;
this->seconds = t.seconds;
}
Time & operator +(Hours & h)
{
hours += h;
if(hours.getH() % 24 == 0)
reset();
return *this;
}
Time & operator +(Minutes & m)
{
minutes += m;
if(minutes.getM() % 60 == 0)
{
seconds.reset();
minutes.reset();
Hours hour(1);
hours += hour;
}
return *this;
}
Time & operator +(Seconds & s)
{
seconds += s;
if(seconds.getS() % 60 == 0)
{
seconds.reset();
minutes += Minutes(1);
}
return *this;
}
void plus(Minutes & m, Seconds & s)
{
*this = *this + s + m;
}
void plus(Hours & h, Seconds & s)
{
*this = *this + s + h;
}
void plus(Hours & h, Minutes & m)
{
*this = *this + m + h;
}
void plus(Hours & h, Minutes & m, Seconds & s)
{
*this = *this + s + m + h;
}
void display()
{
cout<<"Now is : "<<setw(2)<<setfill('0')<<hours.getH()<<":"
<<setw(2)<<setfill('0')<<minutes.getM()<<":"
<<setw(2)<<setfill('0')<<seconds.getS()<<endl;
}
};
int main()
{
Time t(10, 10, 10);
t.display();
t.plus(Hours(13), Minutes(48), Seconds(50));
//you can also try
//t.plus(Hours(13), Minutes(49), Seconds(50));
t.display();
system("pause");
return 0;
}
[/CODE]