首页 > 解决方案 > 我可以在联合中声明运算符吗?

问题描述

关于工会的问题,因为我很少使用它们。

我使用联合来表示 rgb 像素数据,因此可以将其作为连续数组uint8_t或单个 rgb 元素进行访问。(我认为这可能是工会的少数用途之一。)

像这样的东西:

union PixelRGB
{
    uint8_t array[3];
    struct rgb
    {
        uint8_t b;
        uint8_t g;
        uint8_t r;
    };
};

我已经意识到能够在我的像素数据上应用“and”和“or”之类的操作会很好。我想做类似的事情

PixelRGB::operator&=(const PixelRGB other)
{
    this->rgb.r = other.r;
    this->rgb.g = other.g;
    this->rgb.b = other.b;
}

我尝试将这样的运算符放在联合中,但据我所知,这在 C++ 中是不允许的。(编译时我也遇到了编译器错误 - 所以我认为这是不允许的。)

我考虑过的一种可能的解决方案是将联合包装在一个类中,然后将运算符添加到该类中。然而,这对于命名空间/名称范围有些不愉快。

还有其他解决方案吗?

标签: c++operatorsunion

解决方案


您可以在联合内定义运算符,这是可能的

union PixelRGB {
    ...
    PixelRGB& operator&=(const PixelRGB& other) {
        return *this;
    }
};

或外面

PixelRGB& operator&=(PixelRGB& self, const PixelRGB& other) {
    return self;
}

推荐阅读