重载为友员函数。
#include <iostream>
using namespace std;
class Clock
{
private:
int s;
int m;
int h;
public:
void display();
Clock(Clock &);
Clock(int, int, int);
friend Clock operator+(int, Clock&);
friend Clock operator+(Clock&, int);
};
void Clock::display()
{
cout << h << ":" << m << ":" << s << endl;
}
Clock::Clock(Clock&c)
{
m = c.m;
s = c.s;
h = c.h;
}
Clock::Clock(int x, int y, int z)
{
h = x;
m = y;
s = z;
}
Clock operator +(int x,Clock&c)
{
Clock clk = c;
clk.h += c.h;
clk.h %= 24;
if (clk.h < 0)
clk.h += 24;
return clk;
}
Clock operator+(Clock&c, int x)
{
Clock clk = c;
clk.h += c.h;
clk.h %= 24;
if (clk.h < 0)
clk.h += 24;
return clk;
}
void main()
{
Clock one(5, 30, 0);
one.display();
Clock two = one + 4;
two.display();
Clock three = 100 + two;
three.display();
getchar();
}
1382

被折叠的 条评论
为什么被折叠?



