gpt4 book ai didi

c++ - 为枚举结构设置多个属性

转载 作者:太空狗 更新时间:2023-10-29 23:53:53 26 4
gpt4 key购买 nike

我定义了一个像这样的enum结构

class myC {
enum accessClass {
none,
forL,
forM,
forA
};

typedef accessClass AccessType;
AccessType aType;
};

myC obj;

问题是我必须只选择一个成员。但是我想选择多个成员。目前如果我写

obj->aType = forL;
obj->aType = forM;

那么后者将取代第一个。

我想为 enum 结构选择多个项目/成员/属性。

我该怎么办?

最佳答案

使用 bitfield .

enum MyEnum {
A = 1<<0; // 0x01
B = 1<<1; // 0x02
C = 1<<2; // 0x04
D = 1<<3; // 0x08
E = 1<<4; // 0x10
F = 1<<5; // 0x20
...
}

MyEnum m;

m = A; // m = 0x01 (Only A is on)

// Set values by ORing them in.
m |= F; // OR in field F. Now m = 0x21 (A and F are on)

// Set multiple values by ORing them together.
m = (A | C | E); // m = 0x15 (A, C, and E)

// Clear values by ANDing them out.
m &= ~C; // AND out field C. m = 0x11 (A and E are on)

// Test values with AND
if (m & A)
printf("A is set\n");
if (m & B)
printf("B is set\n");

参见“使用位标志”:http://www.dylanleigh.net/notes/c-cpp-tricks.html

关于c++ - 为枚举结构设置多个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8771881/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com