c++ - 枚举器中的按位运算

标签 c++ c++11

<分区>

我需要根据场景将一些额外数据添加到现有枚举代码中。作为示例,我有以下代码:

#include <iostream>

enum Permissions {Readable = 0x4, Writable = 0x2, Executable = 0x1};

int main()
{
Permissions perms = static_cast<Permissions>(Executable | static_cast<Permissions>(29));
std::cout << perms  <<  std::endl;
perms &= ~Permissions::Executable;
std::cout << perms  <<  std::endl;
}

起初我尝试添加数据,然后提取相同的数据 - 但出现编译错误:

$ c++ -std=c++11 try67.cpp
try67.cpp: In function 'int main()':
try67.cpp:9:7: error: invalid conversion from 'int' to 'Permissions' [-fpermissive]
 perms &= ~Permissions::Executable;

方法是否正确,如何消除编译错误?

最佳答案

Is the approach correct and how can we remove the compilation error?

该方法存在问题。如果您仔细使用变量,则可以使用 enum

线

perms &= ~Permissions::Executable;

相当于

perms = perms & ~Permissions::Executable;

编译器错误的原因是按位运算符生成 int 而您正试图将 int 分配给 enum没有 Actor 。

您必须像处理第一个操作一样使用强制转换来消除编译器错误。

perms = static_cast<Permissions>(perms & ~Permissions::Executable);

更新,回应OP的评论

可读 |可写0x6,它不对应于enum中任何标记的值。 因此,如果您使用:

Permissions p1 = Permissions::Readable;
Permissions p2 = Permissions::Writable;

Permissions p3 = static_cast<Permissions>(p1 | p2);

您会遇到 p3 的值与任何已知标记都不匹配的情况。如果您有 if/else block 或 switch 语句,它们期望所有类型为 Permissions 的变量的值是作为已知标记之一,您会注意到代码中的意外行为。

关于c++ - 枚举器中的按位运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53465221/

相关文章:

c++ - boost图形库: named_graph and remove_vertex

c++ - 添加 BMP 灰度 header

c++ - 为什么第一行出现了除零以外的其他值?

c++ - Qt 自定义窗口

c++ - 成员右值引用和对象生命周期

c++ - 嵌套的 openMP 并行化结合 std::thread

c++ - constexpr 函数的 undefined symbol

c++ - 如何在 Visual Studio 2013 中本地使用 SDL

c++ - 迭代器失效规则是否意味着线程安全?

c++ - C++ 中 std::is_trivially_copy_constructible 中的琐碎操作是什么