First of all, I would like to ask if anyone knows a decent site that explains operator overloading pretty well. It's a very confusing topic.. I can't seem to understand. And there seems to be plenty of arguments that overloading makes the program more complicated to read, which is the reason that Java doesn't have it.
Okay, for the actual program..
I was asked to make a program that compares two dates using operator overloading. I'm a mess right now, but I'll post the code anyway.
Its very messy.. and sloppy. It doesn't even compile yet. Please, can anyone give me some helpful hints?
Date(int m, int d, int y);
bool isAfter(Date date1, Date date2); //checks if the date1 is after date2.
bool operator == (const Date &date2); //I have no idea how to use this.. I'm suppose to see if the dates are equal to each other.
Date::Date() //contains default date
Date::Date(int m, int d, int y)
bool Date::isAfter(Date date1, Date date2)
if (date2.year > date1.year)
else if (date2.year < date1.year)
if (date2.month > date1.month)
else if (date2.month < date1.month)
if (date2.day > date1.day)
bool Date::operator == (const Date &date2) //no idea.
Date date1, date2;
cout<<"Enter the first date"<<endl;
cout<<"Enter the second date"<<endl;
Look at Date::Show(). It calls IsAfter(date1, date2), but the parameters (date1, date2) aren't defined anywhere (well, in main() but that doesn't count.). This is because the rest of it is sort of jumbled :) But don't worry about that; it's not too hard to fix. Here are my suggestions:
-make IsAfter() take only 1 Date. So it should be IsAfter(Date otherDate). Then change 'date2.year' (and all the other date2) to just 'year' (or whatever the .* was). Then, change all the date1's to otherDate's. This should work, because IsAfter() is a member function of Date, so if you go date1.IsAfter(someotherdate), IsAfter will be able to access date1's member variables.
-make Date::Show() take 1 Date as a parameter (i.e. Date otherdate - the date to compare against). Then when you call IsAfter(), pass it otherdate.
-in main(), instead of date1.show() go date1.show(date2) - do the same with date2.show().
As for the operator==, what does the == operator do normally? It compares to see if the two are equal, and if they are, then it returns true :) So basically, in the code you would do this:
Hope this helps :)
if((year == date2.year) && (month == date2.month) && (day == date2.day))
P.S. Please don't just copy and paste the code like so many people do (Don't get me wrong, I'm not saying you do). Read through it and learn from it - that's the purpose of the C board ;)
P.P.S. I didn't try the code; it might not work :D It should though, if I'm as perfect as I like to think I am :p