operator ==重载函数失败

时间:2017-03-02 17:49:50

标签: c++ operator-overloading

我在一个简单的时间类中重载了运算符> < ==

double exchange_time::seconds_from_midnight() const {
    return seconds + minutes * 60.0 + hours * 3600.0 + milliseconds / 1000.0;
}

bool exchange_time::operator<(const exchange_time& other) const
{
    return seconds_from_midnight() < other.seconds_from_midnight();
}

bool exchange_time::operator>(const exchange_time& other) const
{
    return seconds_from_midnight() > other.seconds_from_midnight();
}

bool exchange_time::operator==(const exchange_time& other) const
{
    return seconds_from_midnight() == other.seconds_from_midnight();
}

><完美无缺。但是==会产生错误而我的测试失败:

TEST_F(exchange_time_test, comparison) {
    exchange_time et1, et2;
    et1.set("93500001");
    et2.set("93500123");
    EXPECT_TRUE(et2 > et1);
    EXPECT_TRUE(et1 < et2);
    EXPECT_TRUE(et2 == et2);
}

我有什么遗失的吗?

这是我的声明:

class exchange_time {
    public:
        void set(string timestamp);
        unsigned short int get_milliseconds() { return milliseconds; }
        unsigned short int get_seconds() { return seconds; }
        unsigned short int get_minutes() { return minutes; }
        unsigned short int get_hours() { return hours; }
        double seconds_from_midnight() const;
        bool operator<(const exchange_time& other) const;
        bool operator>(const exchange_time& other) const;
        bool operator==(const exchange_time& other) const;
    private:
        unsigned short int milliseconds;
        unsigned short int seconds;
        unsigned short int minutes;
        unsigned short int hours;
};

1 个答案:

答案 0 :(得分:4)

永远不要比较双数的相等性。检查它们是否几乎相等。最常见的方法是使用epsilon来比较值。

bool exchange_time::operator==(exchange_time other)
{
  return abs(seconds_from_midnight() - other.seconds_from_midnight()) < EPS;
}

EPS 的值非常小。如果您需要准确比较,则需要定义自己的 Fraction 类。

修改
EPS 代表Epsilon,它被定义为 Dictionary.com的一个非常小,无关紧要或可忽略不计的数量