有什么方法可以在所有操作类型的基本函数中执行代码?我想执行所有do_card动作共有的行为。换句话说,我想打印游戏状态,但是我想避免在每个单独的do_card函数中复制一个printf,而是只写一次。有没有办法用C来实现呢?

struct CARD {
    int value;
    int cost;
    // This is a pointer to a function that carries out actions unique
    // to this card
    int (*do_actions) (struct GAME_STATE *state, int choice1, int choice2);
};
int do_card0(struct GAME_STATE *state, int choice1, int choice2)
{
    // Operate on state here
}

int do_card1(struct GAME_STATE *state, int choice1, int choice2)
{
    // Operate on state here
}

static struct cardDefinitions[] = {
    {0, 1, do_card0},
    {1, 3, do_card1}
};
int result = cardDefinitions[cardNumber].do_action(state, choice1, choice2);

最佳答案

如果您真的想模拟多态性,可以,那就太丑了。

typedef struct Card_t Card;
typedef struct
{
   void (*print)(Card*);
   int (*do_action)(Card*, struct GameState*, int);
   /* other possibly card-specific functions here */
} CardMethods;

struct Card_t
{
  int value;
  int cost;
  CardMethods* vtab;
};

int stdAct(Card* this, GameState* st, int choice)
{
    this->vtab->print(this);  //do this card's specific print function.
    /* do common actions based on state&choice */
}

int specialPrint1(Card* this)
{
   stdPrint(this); //call parent print function
   printf("something special here");  //add behavior
}

CardMethods standardCard={stdPrint, stdAct};
CardMethods specialCard1={specialPrint1, stdAct};
CardMethods specialCard2={stdPrint, specialAct1};
CardMethods specialCard3={specialPrint2, specialAct2};
static struct cardDefinitions[] = {
 {0, 1, &standardCard},
 {1, 3, &standardCard},
 {2, 3, &specialCard1},
 {2, 4, &specialCard2},
 /*...*/
};


cardDefinitions[i].vtab->do_action(&cardDefinitions[i], state, choice)

此时,您正在执行C++编译器在幕后所做的大部分工作,您也可以只使用C++。

10-08 13:26
查看更多