c++ - 我可以在联合中声明运算符吗?
问题描述
关于工会的问题,因为我很少使用它们。
我使用联合来表示 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;
}
推荐阅读
- c++ - Array not initialized but includes curly brackets
- amazon-web-services - 如何让 Kinesis 使用 OIDC 令牌连接到 http 端点?
- javascript - TypeError:无法读取未定义的属性“参数”
- git - gbp buildpackage 出于某种原因包括主目录
- node.js - 我们如何知道在google OAuth2.0中向哪个用户提供了哪个授权码
- javascript - ErrorException 未定义的偏移量:1,laravel
- cluster-analysis - 如何在 KMeans 中手动设置聚类中心并预测概率而不是类?(或 GMM)
- angular - 选择文件后移动浏览器重新加载
- html - 滚动在移动设备上不起作用 - 它会点击列表中的按钮
- java - Java Spring:注册流程