C++ examples for Class:Class Creation
Create Date class to perform error checking on the initializer values for data members month, day and year.
#include <iostream> #include <stdexcept> class Date {// ww w . j ava2s. c om public: explicit Date(unsigned int = 1, unsigned int = 1, unsigned int = 2000); void nextDay(); // increment date by 1 void print(); friend std::ostream& operator<<(std::ostream& out, Date& d) { return d.printSensible(out); } private: static const size_t MONTHS_IN_YEAR = 12; static const size_t NO_LEAP = 28; static const size_t LEAP = 29; unsigned int DAYS_IN_MONTH[MONTHS_IN_YEAR + 1] = { 0, 31, NO_LEAP, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; unsigned int month; unsigned int day; unsigned int year; bool isLeapYear(unsigned int); std::ostream& printSensible(std::ostream&); }; Date::Date(unsigned int m, unsigned int d, unsigned int y) { if (y > 0) { year = y; } else { throw std::invalid_argument("Year must be a positive number"); } if (m > 0 && m <= 12) { month = m; } else { throw std::invalid_argument("Month must be 1-12"); } DAYS_IN_MONTH[2] = (isLeapYear(year) ? LEAP : NO_LEAP); if (d > 0 && d <= DAYS_IN_MONTH[month]) { day = d; } else { throw std::invalid_argument("Day must be 0-31"); } } // increment date by 1 void Date::nextDay() { if (day < DAYS_IN_MONTH[month]) { day++; } else { day = 1; if (month < MONTHS_IN_YEAR) { month++; } else { month = 1; year++; DAYS_IN_MONTH[2] = (isLeapYear(year) ? LEAP : NO_LEAP); } } } // check whether given year is leap year bool Date::isLeapYear(unsigned int y) { return (y % 4 == 0 || y % 400 == 0 || y % 100 == 0); } // print date in format mm/dd/yyyy void Date::print() { std::cout << month << "/" << day << "/" << year; } std::ostream& Date::printSensible(std::ostream& out) { return out << day << "/" << month << "/" << year; } #include <iostream> int main(int argc, const char *argv[]) { Date d1(11, 30, 2015); for (int i = 0; i < 365; ++i) { d1.nextDay(); std::cout << d1 << std::endl; } return 0; }