比较两种不同结构类型时如何使用全局比较运算符解决C++中的错误

How to use the global comparison operator when comparing two different structure types to resolve the errors in C++

当我尝试比较两个不同结构的成员时,出现以下错误:

error C2676: binary '==': 'main::strRGBSettings' does not define this operator or a conversion to a type acceptable to the predefined operator

error C2678: binary '==': no operator found which takes a left-hand operand of type 'const T1' (or there is no acceptable conversion)

谁能帮忙介绍一下全局比较运算符的使用方法

#include <string>
#include <iostream>

int main()
{
 struct strRGBSettings
    {
        uint8_t red;
        uint8_t green;
        uint8_t blue;
    };

    struct strStandardColors
    {
        static strRGBSettings black() { return { 0x00, 0x00, 0x00 }; }
        static strRGBSettings red() { return { 0xFF, 0x00, 0x00 }; }
        static strRGBSettings blue() { return { 0x00, 0x00, 0xFF }; }
    };

    struct ColorState
    {
        strRGBSettings     RGB;
    };

    ColorState l_colorState;
    if (l_colorState.RGB == strStandardColors::red())
    {
        std::cout << "The color is of type Red " << std::endl;
    }
    return 0;
}

谢谢

如编译器错误所述,您需要为 strRGBSettings 结构定义 operator==

struct strRGBSettings {
    uint8_t red;
    uint8_t green;
    uint8_t blue;
    bool operator==(const strRGBSettings& stg) const {
        return stg.red == red && stg.blue == blue && stg.green == green;
    }
};

如果不能修改struct,定义operator==为非成员函数:

bool operator==(const strRGBSettings& stg1, const strRGBSettings& stg2) const {
    return (stg1.red == stg2.red && stg1.blue == stg2.blue && stg1.green == stg2.green);
}

请注意,此定义不能进入 main 内部,您至少应该能够访问 main 外部的结构。