有什么办法可以在所有动作类型的基本函数中执行代码?我想执行所有do_card操作通用的行为。换句话说,我想打印游戏状态,但我想避免在每个单独的do_card函数中重复printf,而是只写一次。有没有办法在C中实现这一点?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);
'c'中没有装饰器。在调用这些函数之前,可以尝试使用'printf',如果代码中可能的话。它看起来像你有一些'if'或'switch'语句 - 如果消息是相同的并且适用于所有函数,请在调用其中的任何函数之前先将其放回 – 2011-05-04 20:58:09
此代码避免使用目标开关。我希望能够在所有类型中添加行为,但我认为它不可能在C中使用。 – 2011-05-04 21:01:39
您应该尝试给出更具体的示例。我不确定你想在这里避免什么样的代码重复。 – hugomg 2011-05-04 21:03:50