假设有一个怪物类Monster,Monster中包含跑、跳、走、爬等属性。
定义:
static const int a = 1; //跑 1
static const int b = 1 << 1; //跳 10
static const int c = 1 << 2; //走 100
static const int d = 1 << 3; //爬 1000
实例:
Monster m = new Monster();
m.attribute = 0; //m中用于记录属性
赋值
对attribute进行赋值,直接用对应的属性进行或运算既可,如:
m.attribute |= a; //将跑的属性赋予m,则attribute = 1
m.attribute |= d; //将爬的属性赋予m,则attribute = 1001
优点:不怕重复赋值,或已经包含跑的属性,再或上跑的属性,不会改变结果。
判断:
如判断m的属性中是或包含了爬,只要进行与运算既可:
if( m.attribut & d)
return true;
return false;
移除:
移除怪物m中的或一个属性,则进行异或运算:
if ( m.attribut & d)
m.attrubute ^= d;