具有按位分配操作的C ++类型转换

时间:2018-12-17 08:58:33

标签: 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 conversion from ‘int’ to ‘type1_e’

}

2 个答案:

答案 0 :(得分:5)

operator |产生int结果

type1_e(y | x)

y | xint。您正在将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