有什麼辦法可以在所有動作類型的基本函數中執行代碼?我想執行所有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