// date.cpp #include #include "date.h" // Inizializzazione atributo di classe const int Date::days[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // Costruttore Date::Date( int m, int d, int y ) { setDate( m, d, y ); } // Set della data void Date::setDate( int mm, int dd, int yy ) { month = ( mm >= 1 && mm <= 12 ) ? mm : 1; year = ( yy >= 1900 && yy <= 2100 ) ? yy : 1900; // test anno bisestile if ( month == 2 && leapYear( year ) ) day = ( dd >= 1 && dd <= 29 ) ? dd : 1; else day = ( dd >= 1 && dd <= days[ month ] ) ? dd : 1; } // Overloading operatore di preincremento Date & Date::operator++() { helpIncrement(); return *this; // ritorno di un riferimento per creare un lvalue } // Overloading operatore di postincremento // Notare che il parametro fittizio int non ha nome (serve solo // a differenziare il prototipo da quello del preincremento) Date Date::operator++( int ) { Date temp = *this; helpIncrement(); // ritorno del valore precedente all'incremento return temp; // ritorno di un valore } // Aggiunge un dato numero di giorni alla data const Date & Date::operator+=( int additionalDays ) { for ( int i = 0; i < additionalDays; i++ ) helpIncrement(); return *this; // permette l'uso a cascata } // Test anno bisestile bool Date::leapYear( int y ) const { if ( y % 400 == 0 || ( y % 100 != 0 && y % 4 == 0 ) ) return true; // è bisestile else return false; // non è bisestile } // Test fine del mese bool Date::endOfMonth( int d ) const { if ( month == 2 && leapYear( year ) ) return d == 29; // last day of Feb. in leap year else return d == days[ month ]; } // Funzione di ausilio all'incremento void Date::helpIncrement() { if ( endOfMonth( day ) && month == 12 ) { // fine anno day = 1; month = 1; ++year; } else if ( endOfMonth( day ) ) { // fine mese day = 1; ++month; } else // non fine anno o mese; incremento del giorno ++day; } // Overloading operatore di input ostream &operator<<( ostream &output, const Date &d ) { // la seguente dichiarazione static non ha nulla a che fare // con attributi di classe. E' una nozione diversa ... 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; // permette uso a cascata }