How to compare two objects (the calling object and the parameter) in a class?
int Date :: Compare (const Date& d) {
if (year<d.year) {
return -1;
}
else if (year>d.year) {
return 1;
}
else if (month<d.month) {
return -1;
}
else if (month>d.month) {
return 1;
}
// same for day
return 0;
}
Usually, you'lll also want to provide overloaded comparison operators, for example (also within the class definition):
bool operator == (const Date& d) const {
return !Compare(d);
}
bool operator < (const Date& d) const {
return Compare(d)<0;
}
... // consider using boost::operators
PS: There are smarter implementations of Compare()
- just check the other answers. This one is pretty straightforward and readable, but conforms exactly to your specification.
into the class's public
area
bool operator==(const Date& rhs) const {
return
year == rhs.year
&& month == rhs.month
&& day == rhs.day
;
}
Here's how I might implement your Compare function, although the format takes a moment to get used to:
int Date::Compare(const Date& d) const {
return
(year < d.year) ? -1 :
(year > d.year) ? 1 :
(month < d.month) ? -1 :
(month > d.month) ? 1 :
(day < d.day) ? -1 :
(day > d.day) ? 1 :
0;
}
Or perhaps:
template<typename T>
int Compare(T a, T b) {
if (a < b) return -1;
if (b < a) return 1;
return 0;
}
int Date::Compare(const Date& d) const {
int a = Compare(year, d.year);
if (a == 0) a = Compare(month, d.month);
if (a == 0) a = Compare(day, d.day);
return a;
}
I wouldn't use operator==
in Compare, although the answers telling you how to implement operator==
are fine if you want that as well. The reason is that operator==
is clearly going to have to look at the same fields compare does, and if it returns false then Compare will do very similar work again. Efficiency probably isn't an issue, but it duplicates the logic.
And for what it's worth, idiomatic C++ is to implement operator<
and possibly also a consistent operator==
and operator>
, rather than an all-in-one Compare function. The operators are what the standard algorithms use for searching and sorting, and everything else follows. Java chose to do things differently.
Compare object by contents, i.e. in your case the dates are equal of the day, month and year are equal (and perhaps format
- depending on your semantics).
Also, C++ already includes a great facility for object comparison: operator ==
which allows writing clearer code than calling a Compare
method.
By the way, take care with this:
if (d1 == d2)
cout << "The dates are the same";
return (0);
If the condition is true, the cout
line will be executed. The return
will be executed even if the condition is false.