【发布时间】:2018-05-01 02:11:42
【问题描述】:
使用 GCC 4.8.*,当警告 -Wfloat-equal 被激活时,编译器会警告浮点数之间的严格比较,如下例所示:
double x = 3.14159;
double y = 1.11111;
if(x == y) // <-- this induces a warning
{ /* ... */ }
现在,假设我想要一个包含双变量并定义相等运算符的类:
class Complex // (it's only an example)
{
private:
double re;
double im;
public:
bool operator == (Complex const& z) const;
};
bool Complex::operator == (Complex const& z) const
{
return (this->re == z.re) && (this->im == z.im);
}
这完全符合我的预期。当然,当我编译类时它会引发警告。为了避免(因为我理解了警告,感谢编译器,但我想这样做,我不想继续看到警告),我通过这种方式通知编译器:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"
bool Complex::operator == (Complex const& z) const
{
return (this->re == z.re) && (this->im == z.im);
}
#pragma GCC diagnostic pop
好的,我在编译 Complex.cpp 文件时没有收到警告。但是在复数上使用运算符== 仍然很危险,就像在双数上使用运算符== 一样危险(这是存在-Wfloat-equal 选项的原因)。然后,我的问题:
是否有可能出现 GCC 警告(由 -Wfloat-equal 激活),其中在复数上使用运算符 ==? 我要警告的不是运算符的存在,而是用法。
注意:我将对称运算符定义为类成员,但如果可以简化我的预期行为,我愿意拥有一个由 bool operator == (Complex const&,Complex const&) 调用的类函数 bool equals(...) const。
注意:出于兼容性原因,我不使用 C++11。
【问题讨论】:
-
会是错误吗?
-
@iBug:我对给出错误的解决方案很感兴趣,但如果一个简单的警告阻止它们,这对我的夜间构建来说是个问题。
-
我认为,如果 -Wfloat-equal 可以过滤掉与精确浮点字面量的比较,特别是 0.0 和 1.0,那么它的实用性会大大增强。
标签: c++ gcc c++03 pragma gcc-warning