代码之家  ›  专栏  ›  技术社区  ›  user2138149

我可以在联合内声明运算符吗?

  •  0
  • user2138149  · 技术社区  · 7 年前

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

    我使用并集来表示rgb像素数据,因此它可以作为一个连续的数组来访问 uint8_t

    像这样:

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

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

    我试着把这样的操作员放在工会里,但据我所知,C++中不允许这样做。(我在编译时也遇到了一个编译器错误-因此我认为这是不允许的。)

    2 回复  |  直到 7 年前
        1
  •  3
  •   Jans    7 年前

    可以在并集内定义运算符,这是可能的

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

    PixelRGB& operator&=(PixelRGB& self, const PixelRGB& other) {
        return self;
    }
    
        2
  •  0
  •   Victor Padureanu    7 年前

    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++,即使它是由多个编译器支持的。