多SWITCH-CASE结构时的C语言对象方式化解

原创
2016/04/09 22:03
阅读数 179

原有代码:

#include <stdio.h>
int main()
{
    int n=0;
    while(1)
    {
        scanf("%d",&n);
        switch(n)
        {
        case 0:
            printf("STATE0\n");
            break;
        case 1:
            printf("STATE1\n");
            break;
        case 2:
            printf("STATE2\n");
            break;
        default:
            return 0;
        }
    }
    return 0;
}

改造方案:
#include <stdio.h>
#define N 3 //状态值


struct State
{
    int i;
    void (*CreateState)(struct State *s);
    void (*Show)(struct State s);
    void (*StateTrans[N])(struct State s);
};

void StateTrans0(struct State s)
{
    s.i=0;
    s.Show(s);
}

void StateTrans1(struct State s)
{
    s.i=1;
    s.Show(s);
}

void StateTrans2(struct State s)
{
    s.i=2;
    s.Show(s);
}

void Show(struct State s)
{
    printf("State-%d\n",s.i);
}

void CreateState(struct State *s)
{
    s->Show=Show;
    s->StateTrans[0]=StateTrans0;
    s->StateTrans[1]=StateTrans1;
    s->StateTrans[2]=StateTrans2;
}


enum{ST0=0,ST1,ST2}STATE;//枚举状态

int main()
{
    State s;//实例化

    //初始化
    s.CreateState=CreateState;
    s.CreateState(&s);
   
    //模拟状态调用
    while(1)
    {
        scanf("%d",&STATE);   
        if(STATE<0||STATE>2)
        {
            break;
        }
        s.StateTrans[STATE](s);
    }
   
    getchar();
    return 0;
}


展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
1
分享
返回顶部
顶部