我有一个带有两个重载比较运算符(运算符==)的 RGB 颜色类。一种用于 self 类型,一种用于 int (HEX)。
// this one assigns the value correctly
RGB RGB::operator=(const int hex)
{
this->r = (hex>>16 & 0xFF) / 255.0f;
this->g = (hex>>8 & 0xFF) / 255.0f;
this->b = (hex & 0xFF) / 255.0f;
return *this;
}
//--------------------------------------------------------------------------------------
// also works
bool RGB::operator==(const RGB &color)
{
return (r == color.r && g == color.g && b == color.b);
}
// this is evil
bool RGB::operator==(const int hex)
{
float rr = (hex>>16 & 0xFF) / 255.0f;
float gg = (hex>>8 & 0xFF) / 255.0f;
float bb = (hex & 0xFF) / 255.0f;
// if i uncomment these lines then everything is fine
//std::cout<<r<<" "<<rr<<std::endl;
//std::cout<<g<<" "<<gg<<std::endl;
//std::cout<<b<<" "<<bb<<std::endl;
return (r == rr &&
g == gg &&
b == bb);
}
RGB::RGB(int hex)
{
setHex(hex);
}
inline void RGB::setHex(unsigned hex)
{
r = (float)(hex >> 16 & 0xFF) / 255.0f;
g = (float)(hex >> 8 & 0xFF) / 255.0f;
b = (float)(hex & 0xFF) / 255.0f;
}
...然后我在 main.cpp 中进行比较,例如:
RGB a = 0x555555;
bool equals = (a == 0x555555); // returns false
我不知道会发生什么。比较返回 false,但如果我取消注释定义中的 std::cout 行,则该函数按预期工作并返回 true。
这也没有问题:
RGB a = 0x555555;
RGB b = 0x555555;
bool equals = (a == b); // returns true
有人有想法吗?