有什么方法可以在所有操作类型的基本函数中执行代码吗?我想执行所有 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);
最佳答案
与其在每张卡片上调用 do_action,不如将卡片与其他参数一起传递给您定义的另一个函数,调用 do action 方法,然后调用 print state 方法或其他方法
例如
//add a method like this
int process_card(CARD inCard, GAME_STATE *state, int choice1, int choice2)
{
inCard.do_action(state, choice1, choice2);
print_state(state);
}
//last line changes to
process_card(cardDefinitions[card_number], state, choice1, choice2);
肯定会出现错误,我的 C 已经生锈了,但我就是这么想的。
关于C函数修饰/多态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5889698/