#include <iostream>
using namespace std;
class Clock
{
private:
int hour, minute, second;
public:
Clock(int hour = 0, int minute = 0, int second = 0);
Clock & operator++();
Clock operator++(int);
friend ostream & operator<<(ostream & output, const Clock & obj);
};
Clock::Clock(int hour, int minute, int second) :hour(hour), minute(minute), second(second){}
Clock & Clock::operator++()
{
second++;
if (second >= 60)
{
minute += second / 60;
second %= 60;
if (minute >= 60)
{
hour += minute / 60;
minute %= 60;
if (hour >= 24)
hour %= 24;
}
}
return (*this);
}
Clock Clock::operator++(int)
{
Clock old = (*this); //将原来的对象拷贝一份
++(*this);<span style="white-space:pre"> </span> //<span style="color: rgb(51, 51, 51); font-family: Helvetica, Tahoma, Arial, sans-serif; font-size: 14px; line-height: 24px; background-color: rgb(245, 245, 245);">然后调用重载的前置操作符因为*this的对象类型是Clock</span>
return (old);
}
ostream & operator<<(ostream & output, const Clock & obj)
{
output << obj.hour << ":" << obj.minute << ":" << obj.second;
return (output);
}
int main()
{
Clock myClock(23, 59, 59);
cout << "myClock: " << myClock << endl;
cout << "myClock++: " << myClock++ << endl;
cout << "myClock: " << myClock << endl;
cout << "++myClock: " << ++myClock << endl;
cout << "myClock++: " << myClock++ << endl;
cout << "myClock: " << myClock << endl;
return (0);
}
by xusworld
C++的时钟类
最新推荐文章于 2022-11-19 16:51:20 发布