在涉及按位分配操作(例如x | = y&z;)的情况下,我还没有找到一种类型转换的方法。
示例:
#include <stdio.h>
typedef enum type1{
AA = 0,
BB = 1
} type1_e;
int main()
{
type1_e x,y;
y = type1_e(y | x); //working
y |= (type1_e)(y|x); //ERROR: as.cc:15: error: invalid conversion from ‘int’ to ‘type1_e’
}
答案 0 :(得分:5)
operator |
产生int
结果
type1_e(y | x)
y | x
是int
。您正在将int
强制转换为type1_e
。
y |= (type1_e)(y|x);
等效于
y = y | type1_e(y | x);
您正在使用operator |
产生int
结果,然后尝试将其分配给y
的{{1}}。没有铸造就无法做到这一点。
要克服这一点,您可以这样做:
type1_e
与以下相同:
y = type1_e(y | type1_e(y | x));
与以下相同:
y = type1_e(y | y | x);
或:
y = type1_e(y | x);
答案 1 :(得分:2)
|
)的重载。 static_cast
才能正确转换。#include<iostream>
using namespace std;
typedef enum type1{
AA = 0,
BB = 1
} type1_e;
type1_e operator |=(type1_e& x, type1_e y)
{
return x=static_cast<type1_e>(static_cast<int>(x) | static_cast<int>(y));
}
int main()
{
type1_e x = AA, y = BB;
y = type1_e(y | x); //working
std::cout << y << '\n';
x = AA, y = AA;
y |= static_cast<type1_e>(y|x); //also works
std::cout << y << '\n';
}
请参见demo。