程序代码:
#include <iostream>
class datetime
{
public:
datetime( unsigned year, unsigned month, unsigned day, unsigned hour=0, unsigned min=0, unsigned sec=0 )
: year_(year), month_(month), day_(day), hour_(hour), min_(min), sec_(sec)
{
}
bool operator< ( const datetime& dt ) const
{
if(year_<dt.year_) return true;
if(year_>dt.year_) return false;
if(month_<dt.month_) return true;
if(month_>dt.month_) return false;
if(day_<dt.day_) return true;
if(day_>dt.day_) return false;
if(hour_<dt.hour_) return true;
if(hour_>dt.hour_) return false;
if(min_<dt.min_) return true;
if(min_>dt.min_) return false;
return sec_<dt.sec_;
}
bool operator> ( const datetime& dt ) const
{
return dt<*this;
}
bool operator<= ( const datetime& dt ) const
{
return !(dt<*this);
}
bool operator>= ( const datetime& dt ) const
{
return !(*this<dt);
}
bool operator!= ( const datetime& dt ) const
{
return *this<dt || dt<*this;
}
bool operator== ( const datetime& dt ) const
{
return !(*this<dt || dt<*this);
}
private:
unsigned year_, month_, day_, hour_, min_, sec_;
friend std::ostream& operator<< ( std::ostream& os, const datetime& dt );
};
std::ostream& operator<< ( std::ostream& os, const datetime& dt )
{
return os << dt.year_ << '-' << dt.month_ << '-' << dt.day_ << ' ' << dt.hour_ << ':' << dt.min_ << ':' << dt.sec_;
}
using namespace std;
void test( const datetime& a, const datetime& b )
{
ios_base::fmtflags flags_saved = cout.flags();
cout.setf( ios_base::boolalpha );
cout << a << " < " << b << " ? " << (a <b) << '\n';
cout << a << " > " << b << " ? " << (a >b) << '\n';
cout << a << " <= " << b << " ? " << (a<=b) << '\n';
cout << a << " >= " << b << " ? " << (a>=b) << '\n';
cout << a << " != " << b << " ? " << (a!=b) << '\n';
cout << a << " == " << b << " ? " << (a==b) << '\n';
cout.setf( flags_saved, ios_base::boolalpha );
}
int main( void )
{
test( datetime(1998,8,17,9,51,30), datetime(1998,8,17,9,51,31) );
cout << '\n';
test( datetime(1998,8,17,9,51,30), datetime(1998,8,17,9,51,30) );
}