登录
  • 欢迎访问 Sharezer Blog

用位运算做类的属性赋值与判断

Default sharezer 1912次浏览 已收录 0个评论

假设有一个怪物类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;

Sharezer , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明用位运算做类的属性赋值与判断
喜欢 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址