I need to modify this program to have 2 more operators a greater than operator n
ID: 3624518 • Letter: I
Question
I need to modify this program to have 2 more operators a greater than operator named operator>() and a less than operator named operator<() which can see if 2 dates are earlier or later than one another.Here's the program...
#include <iostream>
using namespace std;
class Date
{
private:
int month;
int day;
int year;
public:
Date(int = 7, int = 4, int = 2005);
bool operator==(Date &);
};
Date::Date(int mm, int dd, int yyyy)
{
month = mm;
day = dd;
year = yyyy;
}
bool Date::operator==(Date &date2)
{
if(day == date2.day && month == date2.month && year == date2.year)
return true;
else
return false;
}
int main()
{
Date a(4,1,2007), b(12,18,2008), c(4,1,2007);
if (a==b)
cout << "dates a and b are the same" << endl;
else
cout << "dates a and b are different" << endl;
if (a==c)
cout << "dates a and c are the same" << endl;
else
cout << "dates a and c are different" << endl;
return 0;
}
Explanation / Answer
The operators are as follows:
bool Date::operator>(Date &date2)
{
if(year>date2.year||(year==date2.year&&month>date2.month)||(year==date2.year&&month==date2.month&&day>date2.day))
return true;
else
return false;
}
bool Date::operator<(Date &date2)
{
if(year<date2.year||(year==date2.year&&month<date2.month)||(year==date2.year&&month==date2.month&&day<date2.day))
return true;
else
return false;
}
And your main method has to have a few extra statements to check:
if(a>b)
cout<< "date a is later than b"<< endl;
if(acout<< "date a is earlier than b" <
etc..
That's all !