使用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 equals(...) const
的类函数来调用bool operator == (Complex const&,Complex const&)
。
注意:出于兼容性原因,我不使用C++11。