知识点讲解

  1. 用二进制的每一位来表示一种状态,类似于枚举法
  2. 比枚举更加强大的地方在于,不同的状态可以灵活的进行组合和拆分。

    • 使用或运算符(|)进行组合
    • 使用与运算符(&)进行拆分

示例代码

#include <iostream>
#include <cstdlib>
using namespace std;

#define TL_YAN       0x001L // 00001 盐
#define TL_TANG      0x002L // 00010 糖
#define TL_JIANGYOU  0x004L // 00100 酱油
#define TL_CU        0x008L // 01000 醋
#define TL_LAJIAO    0x010L // 10000 辣椒

typedef long LONG;

// 调料
void TiaoLiao(LONG l)
{
    if (l&TL_YAN)            // 00001 & xxxx1 = 00001
        cout<<"盐"<<endl;

    if (l&TL_TANG)         // 00010 & xxx0x = 00000
        cout<<"糖"<<endl;

    if (l&TL_JIANGYOU)
        cout<<"酱油"<<endl;

    if (l&TL_CU)
        cout<<"醋"<<endl;

    if (l&TL_LAJIAO)
        cout<<"辣椒"<<endl;
}

void main()
{
    cout<<"你需要调料:"<<endl;
    TiaoLiao(TL_LAJIAO | TL_TANG);
    system("pause");
}

最后修改:2021 年 05 月 29 日 02 : 34 PM
如果觉得我的文章对你有用,请随意赞赏