// // dateclass2.cpp // // This file contains the definition of a date // class that is more realistic than the one in // dateclass1.cpp. // #include class date { private: int month; int day; int year; int isLeapYear(int year); int daysInMonth(int month, int year); int legalDate(int checkMonth, int checkDay, int checkYear); public: date(); ~date(); int getDay(); int getMonth(); int getYear(); int set(int newMonth, int newDay, int newYear); void print(); int JulianDay(); }; // // This is the definition of the constructor function. // date::date() { month = 0; day = 0; year = 0; } // // This is the definition of the destructor function. // date::~date() { } // // These are the definitions of the three accessor // functions. // int date::getDay() { return day; } int date::getMonth() { return month; } int date::getYear() { return year; } // // isLeapYear returns true if the year passed // to it is a leap year (according to the // Gregorian calendar). // int date::isLeapYear(int year) { if ((year % 4) == 0) { if ((year % 400) == 0) { return 0; } else { return 1; } } else { return 0; } } // daysInMonth expects month to be in the // range 1 to 12. It returns the number of // days in that month. It knows how to // handle February in leap years correctly. // int date::daysInMonth(int month, int year) { if (month < 1 || month > 12) { return 0; } if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { return 31; } else if (month == 4 || month == 6 || month == 9 || month == 11) { return 30; } else if (month == 2 && isLeapYear(year)) { return 29; } else { return 28; } } // // legalDate returns true if the date is correct. // int date::legalDate(int checkMonth, int checkDay, int checkYear) { if (checkMonth < 1 || checkMonth > 12) { return 0; } if (checkDay > daysInMonth(checkMonth, checkYear)) { return 0; } return 1; } // // set sets the date object to the month, day, // and year passed as parameters if it's a // legal date. Otherwise, it leaves the date // unchanged. It returns true if the date was // changed and false otherwise. // int date::set(int newMonth, int newDay, int newYear) { if (legalDate(newMonth, newDay, newYear)) { month = newMonth; day = newDay; year = newYear; return 1; } return 0; } // // print prints a date in the usual month/day/year // form. // void date::print() { cout << month << "/" << day << "/" << year; return; } // // JulianDay returns the number of the date's // day in the year. // int date::JulianDay() { int index; int dayCount = 0; for (index = 1; index < month; index++) { dayCount += daysInMonth(index, year); } dayCount += day; return dayCount; }