C语言的设计模式--小例子

#include <stdio.h>
int Player_IsDead(struct Player* player);

struct Player {
int HP;//血量
};
struct Warrior {
struct Player base;
int Attack;//攻击力
int Defensive;//防御力
};
struct Mage {
struct Player base;
int MP;//魔法值
int Range;//施法范围
};
//玩家挂了吗?
int Player_IsDead(struct Player* player) {
return (player->HP==0) ? 1 : 0;
}
//吃血
void Player_DrinkRedBottle(struct Player* player, int bottle_level) {
if( bottle_level == 1 ) player->HP += 100;//小瓶
else if( bottle_level == 2 ) player->HP += 500;//大瓶
}


int main(int argc, char *argv[])
{
    struct Warrior w;
    struct Mage m;
    //战士没挂就吃个小血瓶
    w.base.HP = 10 ;

    if( !Player_IsDead((struct Player*)&w) ) {//算不算向上转型呢?
    printf("Warrior w is not dead \n") ;
     printf("the w's HP is %d now\n" , w.base.HP) ;
    Player_DrinkRedBottle((struct Player*)&w, 1);
    printf("after drinking a bottle, the w's HP is %d now\n" , w.base.HP) ;
    }

    m.base.HP = 0 ;
    //法师没挂就吃个大血瓶
    if( !Player_IsDead((struct Player*)&m) ) {

    Player_DrinkRedBottle((struct Player*)&m, 2);
    }else{
       printf("Mage m is dead \n") ;
    }

    return 0;
}

参考:http://www.zhihu.com/question/20081346/answer/15829006

你可能感兴趣的:(C语言的设计模式--小例子)