當我嘗試比較兩個不同結構的成員時,出現以下錯誤:
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;
}
謝謝
uj5u.com熱心網友回復:
正如編譯器錯誤所說,您需要operator==為您的strRGBSettings結構定義:
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;
}
};
如果不能修改結構體,定義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。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/385120.html
上一篇:std::unique_ptr如何處理類中的原始指標/參考?
下一篇:C 11關于*begin(a)
