重载多见于符合类型, C++提供的运算符只能是单个运算的, 就像你说的时间一样, 必须要有运算符重载才能保证加减乘除赋值之类的,
这是我以前练习的时候写的, 希望对你有帮助
程序代码:
//重载输入输出练习
#include <iostream>
#include <iomanip>
using namespace std;
class Time
{
public:
Time();
Time(int x, int y):i(x), j(y){}
~Time();
friend ostream& operator<<(ostream& sc, Time& c);
friend istream& operator>>(istream& sr, Time& c);
Time operator+(Time& c)
{
Time t;
t.i = i + c.i;
if(j + c.j > 59)
{
++t.i;
t.j = (j + c.j) - 60;
}
return t;
}
Time operator++()//前++
{
if(j > 59)
{
j -= 60;
++i;
}
else
{
++j;
}
return *this;
}
// Time operator++(int)
private:
int i;
int j;
};
Time::Time()
{
i = 0;
j = 0;
}
Time::~Time()
{
}
ostream& operator<<(ostream& sc, Time& c)
{
sc << setw(2) << setfill('0') << c.i << ":" << setw(2) << setfill('0') << c.j << endl;
return sc;
}
istream& operator>>(istream& sr, Time& c)
{
sr >> c.i >> c.j;
return sr;
}
int main(void)
{
Time t1, t2;
cin >> t1 >> t2;
Time t3 = t1 + t2;
cout << t1 << t2 << endl << t3;
for(int i = 0; i < 60; ++i)
{
cout << t3++;
}
return 0;
}