旗,枚举(C) [英] Flags, enum (C)

查看:119
本文介绍了旗,枚举(C)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是很习惯用旗帜编程,但我想我刚刚发现的情况下,他们会是有用的:

I'm not very used to programming with flags, but I think I just found a situation where they'd be useful:

我有一对夫妇说自己注册为听众对某些事件的对象。他们为依赖于它们被构造时被发送给他们的可变注册事件。我认为,一个不错的方法,这样做会给人以位或连接的变量,像这样的:TAKES_DAMAGE | GRABBABLE |液体等。然后,在构造函数中,对象可以检查设置什么标志和注册它自身作为监听器是的人。

I've got a couple of objects that register themselves as listeners to certain events. What events they register for is dependent on a variable that is sent to them when they are constructed. I think a nice way to do this would be to send bitwise OR connected variables, like such: TAKES_DAMAGE | GRABBABLE | LIQUID, etc. Then, in the constructor, the object can check what flags are set and register it self as listener for the ones that are.

但是,这是我感到困惑。 preferably,这些标志将是一个枚举。但是,这也是个问题。如果我们有这些标志:

But this is where I get confused. Preferably, the flags would be in an enum. But that is also a problem. If we have got these flags:

enum
{
    TAKES_DAMAGE,/* (0) */
    GRABBABLE, /* (1) */
    LIQUID, /* (2) */
    SOME_OTHER /* (3) */
};

然后发送该标志SOME_OTHER(3)将是相同的发送GRABBABLE | LIQUID,将不是吗?

Then sending the flag SOME_OTHER (3) will be the same as sending GRABBABLE | LIQUID, will it not?

究竟如何做你处理这东西?

How exactly do you deal with this stuff?

推荐答案

您枚举需要成为两个大国:

Your enumeration needs to be powers of two :

enum
{
    TAKES_DAMAGE = 1,
    GRABBABLE = 2,
    LIQUID = 4,
    SOME_OTHER = 8
};

另外,在一个更​​易读的方式:

Or in a more readable fashion :

enum
{
    TAKES_DAMAGE = 1 << 0,
    GRABBABLE = 1 << 1,
    LIQUID = 1 << 2,
    SOME_OTHER = 1 << 3
};

为什么呢?因为你希望能够标志没有重叠结合,也能够做到这一点:

Why ? Because you want to be able to combine flags with no overlapping, and also be able to do this:

if(myVar & GRABBABLE)
{
    // grabbable code
}

...如果枚举值看起来像这里面的作品:

... Which works if the enumeration values look like this :

 TAKES_DAMAGE: 00000001
 GRABBABLE:    00000010
 LIQUID:       00000100
 SOME_OTHER:   00001000

所以,说你已经设置 myVar的 GRABBABLE | TAKES_DAMAGE ,这里的工作原理是当你需要检查GRABBABLE标志:

So, say you've set myVar to GRABBABLE | TAKES_DAMAGE, here's how it works when you need to check for the GRABBABLE flag:

 myVar:     00000011
 GRABBABLE: 00000010 [AND]
 -------------------
            00000010 // non-zero => converts to true

如果您想设置 myVar的液体| SOME_OTHER ,该操作将导致:

If you'd set myVar to LIQUID | SOME_OTHER, the operation would have resulted in :

 myVar:     00001100
 GRABBABLE: 00000010 [AND]
 -------------------
            00000000 // zero => converts to false

这篇关于旗,枚举(C)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆