位運算的使用例子

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;
}
相關文章
相關標籤/搜索