我可以在工会内声明运算符吗?

Can I declare operators inside a union?

本文关键字:运算符 声明 我可以      更新时间:2023-10-16

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

我使用联合来表示 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++是不允许的。(我在编译时也遇到了编译器错误 - 因此我认为这是不允许的。

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

还有其他解决方案吗?

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

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

或外部

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

问题不在于操作员,而在于您访问联合的方式。您可以尝试以下组合:

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

PixelRGB& operator&=(PixelRGB& self, const PixelRGB& other) {
    self.r = other.r;
    self.g = other.g;
    self.b = other.b;
    return self;
}

或者这个:

union PixelRGB
{
    uint8_t array[3];
    struct {
        uint8_t b;
        uint8_t g;
        uint8_t r;
    };
    PixelRGB& operator&=( const PixelRGB& other) {
        r = other.r;
        g = other.g;
        b = other.b;
        return *this;
    }
};

或者这个:

union PixelRGB
{
    uint8_t array[3];
    struct {
        uint8_t b;
        uint8_t g;
        uint8_t r;
    };
    PixelRGB& operator&=( const PixelRGB& other);
};

PixelRGB& PixelRGB::operator&=( const PixelRGB& other) {
    r = other.r;
    g = other.g;
    b = other.b;
    return *this;
}

注意:匿名结构已在 C11 中引入

https://en.cppreference.com/w/c/language/struct

但它在C++中不是标准的,即使它被多个编译器支持。