Code:
#include <iostream>
using namespace std;
class Date {
friend ostream &operator<<( ostream &, const Date & );
public:
Date( int m = 1, int d = 1, int y = 1);
void setDate( int, int, int );
Date &operator++();
Date operator++( int );
const Date &operator+=( int );
bool leapYear( int );
bool endOfMonth( int );
private:
int day;
int month;
int year;
static const int days[];
void helpIncrement();
};
const int Date::days[] = { 0, 31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31 };
Date::Date( int m, int d, int y ) { setDate( m, d, y ); }
void Date::setDate( int mm, int dd, int yy )
{
month = ( mm >= 1 && mm <= 12 ) ? mm : 1;
year = ( yy >= 1900 && yy <= 2100 ) ? yy : 1900;
if ( month == 2 && leapYear( year ) )
day = ( dd >= 1 && dd <= 29 ) ? dd : 1;
else
day = ( dd >= 1 && dd <= days[ month ] ) ? dd : 1;
}
Date &Date::operator++()
{
helpIncrement();
return *this;
}
Date Date::operator++( int )
{
Date temp = *this;
helpIncrement();
return temp;
}
const Date &Date::operator+=( int additionDays )
{
for ( int i = 0; i < additionDays; i++ )
helpIncrement();
return *this;
}
bool Date::leapYear( int y )
{
if ( y % 400 == 0 || ( y % 100 != 0 && y % 4 == 0) )
return true;
else
return false;
}
bool Date::endOfMonth( int d )
{
if ( month == 2 && leapYear( year ) )
return d == 29;
else
return d == days[ month ];
}
void Date::helpIncrement()
{
if ( endOfMonth( day ) && month == 12 ) {
day = 1;
month = 1;
++year;
}
else if ( endOfMonth( day ) ) {
day = 1;
++month;
}
else
++day;
}
ostream &operator<<( ostream &output, const Date &d )
{
static char *monthName[ 13 ] = { "", "January",
"February", "March", "April", "May", "June",
"July", "August", "September", "October",
"November", "December" };
output << monthName[ d.month ] << ' '
<< d.day << ", " << d.year;
return output;
}
int main()
{
Date d1, d2( 12, 27, 1992 ), d3( 0, 99, 3451 );
cout << "d1 is " << d1
<< "\nd2 is " << d2
<< "\nd3 is " << d3 << "\n\n";
cout << "d1 += 5 is " << ( d1 += 5 ) << "\n\n";
d3.setDate( 12, 20, 1999 );
cout << "d3 is " << d3;
cout << "\n++d3 is " << ++d3 << "\n\n";
Date d4( 4, 16, 2006 );
cout << "Testing the preincrement operator:\n"
<< " d4 is " << d4 << "\n"
<< "++d4 is " << ++d4 << "\n"
<< " d4 is " << d4 << "\n\n";
cout << "Testing the postincrement operator:\n"
<< " d4 is " << d4 << "\n"
<< "d4++ is " << d4++ << "\n"
<< " d4 is " << d4 << endl;
return 0;
}
The output
Code:
d1 is January 1, 1900
d2 is December 27, 1992
d3 is January 1, 1900
d1 += 5 is January 6, 1900
d3 is December 20, 1999
++d3 is December 21, 1999
Testing the preincrement operator:
d4 is April 17, 2006
++d4 is April 17, 2006
d4 is April 17, 2006
Testing the postincrement operator:
d4 is April 18, 2006
d4++ is April 17, 2006
d4 is April 18, 2006
The d4 data is very strange...... What's the problem with it?