繁体   English   中英

使用按位分配操作的C ++类型转换

[英]C++ typecasting with bitwise assignement operation

我没有找到一种方法来进行类型转换,其中涉及按位赋值操作(例如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’

}

operator | 产生一个int结果

type1_e(y | x)

y | x y | x是一个int 您明确地将该inttype1_e


y |= (type1_e)(y|x);

相当于

y = y | type1_e(y | x);

您正在使用operator | 产生一个int结果,然后尝试将其分配给type1_e y 没有施法,你不能这样做。


为了克服这个问题,你可以这样做:

y = type1_e(y | type1_e(y | x));

这与:

y = type1_e(y | y | x);

这与:

y = type1_e(y | x);

要么:

  y = static_cast<type1_e>(y | x);
  • 您可以为按位OR( | )编写一个适用于枚举的重载。
  • 您还必须使用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'; 

}

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM