// date.C #include // for the object cout #include #include // for class system_clock #include // for the function localtime and structure tm #include "date.h" // The implementation file always includes the header file. using namespace std; // Definition of static data member const int date::length[] { 0, // dummy, so that January will have subscript 1 31, // January 28, // February. Pretend there are no leap years. 31, // March 30, // April 31, // May 30, // June 31, // July 31, // August 30, // September 31, // October 30, // November 31 // December }; // The constructor installs 3 valid values into a newborn date object, // or it throws an exception. date::date(int init_month, int init_day, int init_year) : year {init_year}, month {init_month}, day {init_day} { if (month < 1 || month > 12) { cerr << "Bad month " << init_month << "\n"; exit(EXIT_FAILURE); } if (day < 1 || day > length[month]) { cerr << "Bad month " << init_month << " and day " << init_day << "\n"; exit(EXIT_FAILURE); } } date::date() // Default constructor puts today's date into the newborn object. { const auto now {chrono::system_clock::now()}; const time_t t {chrono::system_clock::to_time_t(now)}; const tm *const p {localtime(&t)}; year = p->tm_year + 1900; month = p->tm_mon + 1; day = p->tm_mday; } int date::monthsInYear() { return size(length) - 1; // number of months in a year } void date::print() const // This member function can't change the date object. { cout << month << "/" << day << "/" << year; } void date::next(int n) // Move forward n days (or backward if n is negative). { if (n >= 0) { for (int i {0}; i < n; ++i) { next(); // Call the other next function, the one with no argument } } else { for (int i {0}; i < -n; ++i) { prev(); // Move backward one day } } } void date::next() // Move this date object one day into the future. { if (day < length[month]) { ++day; } else { day = 1; // Advance into the next month. if (month < 12) { ++month; } else { month = 1; // Advance into the next year. ++year; } } } void date::prev(int n) // Move backward n days. { for (int i {0}; i < n; ++i) { prev(); } } void date::prev() // Move this date object one day into the past. { if (day > 1) { --day; } else { // Move to last day of previous month if (month > 1) { --month; } else { month = 12; // Move to previous year --year; } day = length[month]; } }