#include<iostream>
using namespace std;
class Clock{ int hour,minute,second;
public:
Clock(int hour=0,int minute=0,int second=0) ;
void showtime()const;
Clock& operator++();
Clock operator++(int);
};
Clock::Clock(int hour,int minute,int second) 切记带默认形参的构造函数,声明时带参数,但定义时不需要带参数,,,
{ if(0<=hour&&hour<24&&0<=minute&&minute<60&&0<=second&&second<60)
{ this->hour=hour;
this->minute=minute;
this->second=second;
}
else cout<<"Time error!"<<endl;
}
Clock &Clock::operator++()返回值为当前对象的引用。
{ second++;
if(second>=60)
{ second-=60;
minute++;
if(minute>=60)
{minute-=60;
hour++;
hour%=24;
}
}
return *this;
}
Clock Clock::operator++(int)返回值不是当前对象的引用。
{ Clock old=*this;
++(*this);
return old;
}
void Clock::showtime() const
{ cout<<this->hour<<":"<<this->minute<<":"<<this->second<<endl;
}
int main()
{ Clock c1(23,59,59);
c1.showtime();
(c1++).showtime();
(++c1).showtime();
//system("pause");
}
运算符重载
最新推荐文章于 2012-11-07 12:53:32 发布