位运算的使用例子

class Data
{
public:
    enum  Permission
    {
        allowSelect = 1 << 0,
        allowUpdate = 1 << 1,
        allowInsert = 1 << 2,
        allowDelete = 1 << 3
    };
public:
    Data():flag(0){};
    ~Data(){};

    /*添加某权限*/
    void enable(int permission)
    {
        flag |= permission;
    }
    /*删除某权限*/
    void disable(int permission)
    {
        flag ^= permission;
    }

    /*是否拥有某些权限*/
    bool isAllow(int permission)
    {
        return (flag&permission) == permission;
    }

    /*是否没有某些权限*/
    bool isNotAllow(int permission)
    {
        return (flag&permission) == 0;
    }
    /*是否公拥有某些权限*/
    bool isOnlyAllow(int permission)
    {
        return flag == permission;
    }

    int getPermission() const
    {
        return flag;
    }

    void setPermission(int permission)
    {
        flag = permission;
    }

private:
    int flag;
};

int main()
{
    Data d;
    //设置权限
    d.setPermission(Data::allowSelect|Data::allowUpdate);
    //是否拥有insert、delete权限
    d.isAllow(Data::allowInsert|Data::allowDelete);
    return 0;
}

 

posted @ 2018-07-23 16:30  -南  阅读(146)  评论(0编辑  收藏  举报