#include <iostream>
using namespace std;
//一个时间类,有三个数据成员,时分秒,运用运算符重载实现两个时间对象或一个对象的运算。(都以秒为单位)
class Time
{
public:
Time():hour(0),minute(0),second(0) {}
Time(int h,int m,int s) {
hour=(h>=24||h<0)?0:h;
minute=(m>=60||m<0)?0:m;
second=(s>=60||s<0)?0:s;
}
Time operator+(Time &);
Time operator-(Time &);
Time operator++();
Time operator--();
bool operator>(Time &);
bool operator<(Time &);
friend ostream& operator << (ostream& output, Time & c);
private:
int hour;
int minute;
int second;
};
bool Time::operator>(Time &t){
if(hour>t.hour){
return true;
}else if(hour<t.hour){
return false;
}else{
if(minute>t.minute){
return true;
}else if(minute<t.minute){
return false;
}else{
if(second>t.second){
return true;
}else{
return false;
}
}
}
return false;
}
bool Time::operator<(Time &t){
if(hour<t.hour){
return true;
}else if(hour>t.hour){
return false;
}else{
if(minute<t.minute){
return true;
}else if(minute>t.minute){
return false;
}else{
if(second<t.second){
return true;
}else{
return false;
}
}
}
return false;
}
Time Time::operator-(Time &t){
int h,m,s;
s = second - t.second;
m = minute - t.minute;
h = hour - t.hour;
if(s<0){
s += 60;
m--;
}
if(m<0){
m +=60;
h--;
}
while ( h < 0 ){
h += 24;
}
Time t0(h,m,s);
return t0;
}
Time Time::operator--(){
int h,m,s;
s = second - 1;
m = minute;
h = hour;
Time t0(h,m,s);
return t0;
}
Time Time::operator++(){
int h,m,s;
s = second + 1;
m = minute;
h = hour;
Time t0(h,m,s);
return t0;
}
Time Time::operator+( Time &t )
{
int h, m, s;
s = second + t.second;
m = minute + t.minute;
h = hour + t.hour;
if ( s > 59 )
{
s -= 60;
m++;
}
if ( m > 59 )
{
m -= 60;
h++;
}
while ( h > 23 )
h -= 24;
Time t0( h, m, s );
return(t0);
}
ostream & operator <<( ostream & output, Time & c )
{
output << c.hour << "-" << c.minute << "-" << c.second << endl;
return(output);
}
void testadd(){
int hour,minute,second;
cin>>hour>>minute>>second;
Time t1(hour,minute,second);
cin>>hour>>minute>>second;
Time t2(hour,minute,second);
Time t3=t1+t2;
cout<<"t1+t2=";
cout<<t3;
}
void testsub(){
int hour,minute,second;
cin>>hour>>minute>>second;
Time t1(hour,minute,second);
cin>>hour>>minute>>second;
Time t2(hour,minute,second);
Time t3=t1-t2;
cout<<"t1-t2=";
cout<<t3;
}
void testcomparebig(){
Time t1(1,1,1);
Time t2(2,2,2);
cout<<"t1>t2=";
if(t1>t2){
cout<<"true"<<endl;
}else{
cout<<"false"<<endl;
}
}
void testcomparesmall(){
Time t1(1,1,1);
Time t2(2,2,2);
cout<<"t1<t2=";
if(t1<t2){
cout<<"true"<<endl;
}else{
cout<<"false"<<endl;
}
}
int main()
{
testcomparebig();
testcomparesmall();
return 0;
}
c++ 一个时间类,有三个数据成员,时分秒,运用运算符重载实现两个时间对象或一个对象的运算。(都以秒为单位)
最新推荐文章于 2023-11-06 09:52:48 发布