我可以在工会内声明运算符吗?
Can I declare operators inside a union?
关于工会的问题,因为我很少使用它们。
我使用联合来表示 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++中不是标准的,即使它被多个编译器支持。
相关文章:
- 在哪里声明结构运算符重载
- 让某个类的 '=' 运算符在声明时运行构造函数
- 为什么我在声明对象数组时不能使用 -> 运算符?
- 在一个指令中声明更多指针的运算符优先级
- 类模板中文本运算符的友元声明
- 新运算符分配的大小大于声明的大小.为什么
- 统一初始化是隐式发生的,即使 int 强制转换运算符是使用 explicit 关键字声明的.原因是什么?
- 为什么我不能定义一元运算符,然后在 MSVC 的模板类中声明具有相同名称的友元二进制运算符?
- 为什么重载运算符>在参数声明 const 时不起作用?
- Ho 在标头中声明是结构中的重载运算符?
- 是否可以将引用类型别名与指针运算符一起使用来声明对指针的引用?
- 二元运算符声明的'static'关键字
- 将默认赋值运算符声明为 constexpr:哪个编译器是正确的?
- 如何将 decltype 应用于运算符 [] 声明中的成员函数
- C++重载赋值运算符声明中做什么?
- 如何阅读此运算符声明和实现
- 如何将 lambda 的运算符 () 声明为 noreturn?
- 错误:"运算符"声明为非函数
- 错误:将"运算符<<"声明为非函数|
- 将"运算符<<声明为非函数