我需要根据场景将一些额外数据添加到现有枚举代码中。作为示例,我有以下代码:
#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
的变量的值是作为已知标记之一,您会注意到代码中的意外行为。