0

I don't know if I'm really tired but this piece of code is giving me (logic?) problems while running unit tests. Does anything looks wrong in the following piece of code?

bool Date::operator <= (const Date& d) const {
    if (this != &d) {         
        if (day > d.day)
            return false;
        if (hour > d.hour)
            return false;
        if (minute > d.minute)
            return false;
        if (second > d.second)
            return false;
    }

    return true;
}

Just for testing, I replaced it with this (ugly) version and all the tests passed...

bool Date::operator <= (const Date& d) const {
    if (this != &d) {
        long a = (86400 * day) + (3600 * hour) + (60 * minute) + second;
        long b = (86400 * d.day) + (3600 * d.hour) + (60 * d.minute) + d.second;

        return a <= b;
    }

    return true;
}

Anyone could help? Thanks!

4

2 回答 2

5

I would leverage the lexicographical comparisons available to std::tie to implement bool operator< and one of bool operator== or bool operator>, then implement bool operator<= in terms of the other two.

#include <tuple>

....

bool Date::operator<(const Date& rhs) const
{
    return std::tie(day, hour, minute, second) < 
           std::tie(rhs.day, rhs.hour, rhs.minute, rhs.second);
}

and so on. Altenratively, you can implement bool operator<= directly using std::tie in the same manner.

于 2013-07-09T04:32:41.947 回答
4

That cannot work. For example, if day < d.day but hour > d.hour, you'll return false, which is incorrect.

What you want is this:

bool Date::operator <= (const Date& d) const {
    if (this != &d) {
        if (day < d.day)
            return true;
        if (day > d.day)
            return false;
        if (hour < d.hour)
            return true;
        if (hour > d.hour)
            return false;
        if (minute < d.minute)
            return true;
        if (minute > d.minute)
            return false;
        if (second > d.second)
            return false;
    }
    return true;
}
于 2013-07-09T03:29:33.420 回答