Answer to Question #329954 in C++ for mak

Question #329954

Write a program to implement the Date class which has three data members named day, month and year.

 

1.  Provide a constructor, which takes arguments (you may set values of data members to 0).

 

2.  Write getter and setter functions (input and show functions) for the Date class.

3.  Also write a member function void CompareDates(Date d1, Date d2) which tells which date comes first.

 

Example output:

13/11/2009 comes before 20/12/2009



1
Expert's answer
2022-04-19T03:08:21-0400
#include <iostream>
using namespace std;


class Date {
public:
    Date(int d=0, int m=0, int y=0);
    int getDay() const;
    void setDay(int d);
    int getMonth() const;
    void setMonth(int m);
    int getYear() const;
    void setYear(int y);
    void show() const;
    static void CompareDates(Date d1, Date d2);


private:
    int day;
    int month;
    int year;    
};


Date::Date(int d, int m, int y) {
    setDay(d);
    setMonth(m);
    setYear(y);
}


int Date::getDay() const {
    return day;
}


void Date::setDay(int d) {
    if (d < 0 || d > 31) {
        day = 0;
    }
    else {
        day = d;
    }
}


int Date::getMonth() const {
    return month;
}


void Date::setMonth(int m) {
    if (m < 0 || m > 12) {
        month = 0;
    }
    else {
        month = m;
    }
}


int Date::getYear() const {
    return year;
}


void Date::setYear(int y) {
    year = y;
}


void Date::show() const {
    cout << day << '/' << month << '/' << year;
}


void Date::CompareDates(Date date1, Date date2) {
    int d1 = date1.year*372 + date1.month*31 + date1.day;
    int d2 = date2.year*372 + date2.month*31 + date2.day;


    if (d1 < d2) {
        date1.show();
        cout << " comes before ";
        date2.show();
        cout << endl;
    }
    else if (d1 > d2) {
        date1.show();
        cout << " comes after ";
        date2.show();
        cout << endl;
    }
    else { 
        cout << "The dates are the same" << endl;
    }
}


int main() {
    Date d1(13, 11, 2009);
    Date d2(20, 12, 2009);

    Date::CompareDates(d1, d2);

    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS