我超载运营商>
<
==
在一个简单的时间等级。运营商==超载功能失败
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;
};
'double seconds_from_midnight();''double's是不精确的。一个可以是1.000000000001,另一个可以是0.9999999999999。更多这里:[浮点数学是否被破坏?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – user4581301
[浮点数学是否被破坏?](http:/ /stackoverflow.com/questions/588004/is-floating-point-math-broken) –
但在这种情况下字面意思是相同的数字 – user2717954