Declare the class Date, consisting of data members are day, month and year. The member functions are setdate() to assign the value for data members, Month() to find the string for the month data member and show() to display the date.
#include <iostream>
#include <stdexcept>
using namespace std;
class Date {
private:
int day;
int month;
int year;
void validate(int day, int month, int year);
public:
Date(int day=1, int month=1, int year=1970);
~Date();
void setDate(int day, int month, int year);
const string& Month() const;
void show();
};
Date::Date(int day, int month, int year) {
validate(day, month, year);
this->day = day;
this->month = month;
this->year = year;
}
Date::~Date() {
}
void Date::validate(int day, int month, int year) {
bool isValid;
if (year>=1900 && year<=9999) {
if(month>=1 && month<=12) {
if ((day>=1 && day<=31) && (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)) {
isValid = true;
} else if ((day>=1 && day<=30) && (month==4 || month==6 || month==9 || month==11)) {
isValid = true;
} else if ((day>=1 && day<=28) && (month==2)) {
isValid = true;
} else if (day==29 && month==2 && (year%400==0 ||(year%4==0 && year%100!=0))) {
isValid = true;
} else
isValid = false;
} else {
isValid = false;
}
} else {
isValid = false;
}
if ( isValid == false ) {
throw(domain_error("Date is invalid"));
}
}
void Date::setDate(int day, int month, int year) {
validate(day, month, year);
this->day = day;
this->month = month;
this->year = year;
}
const string& Date::Month() const {
static const string monthsList[] = {"January","February","March","April","May","June","July","August","September","October","November","December"};
return monthsList[month-1];
}
void Date::show() {
cout << this->Month() << " " << this->day << ", " << this->year << endl;
}
int main() {
Date date1(18, 06, 1997);
Date date2;
date2.setDate(12, 12, 2012);
date1.show();
date2.show();
return 0;
}
Comments
Leave a comment