C++ C++;按位赋值操作的类型转换
我还没有找到一种涉及按位赋值操作(例如x |=y&z;)的类型转换方法 例如:C++ C++;按位赋值操作的类型转换,c++,operator-keyword,C++,Operator Keyword,我还没有找到一种涉及按位赋值操作(例如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 conversio
#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’
}
#包括
类型定义枚举类型1{
AA=0,
BB=1
}类型1_e;
int main()
{
类型1_e x,y;
y=类型1_e(y | x);//工作
y |=(type1_e)(y | x);//错误:as.cc:15:错误:从“int”到“type1_e”的转换无效
}
运算符|
生成一个int
结果
type1_e(y | x)
y | x
是一个int
。您正在显式地将int
转换为type1\e
相当于
y = y | type1_e(y | x);
您正在使用运算符|
生成int
结果,然后尝试将该结果分配给y
,即type1\e
。没有演员你就做不到
要克服这一点,您可以这样做:
y = type1_e(y | type1_e(y | x));
这与:
y = type1_e(y | y | x);
y = type1_e(y | x);
这与:
y = type1_e(y | y | x);
y = type1_e(y | x);
或:
y=static_cast(y | x);
- 可以为适用于枚举的按位或(
)编写重载李>|
- 您还必须使用
进行正确转换static\u cast
#包括
使用名称空间std;
类型定义枚举类型1{
AA=0,
BB=1
}类型1_e;
类型1_e运算符|=(类型1_e&x,类型1_e y)
{
返回x=静态施法(静态施法(x)|静态施法(y));
}
int main()
{
类型1_e x=AA,y=BB;
y=类型1_e(y | x);//工作
STD::CUT可能想考虑编写这个操作符<代码> CONTXPRPR < /代码>。
#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';
}