C函数修饰/多态

标签 c pointers polymorphism decorator abstraction

有什么方法可以在所有操作类型的基本函数中执行代码吗?我想执行所有 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/

相关文章:

c++ - 使用性能分析工具的 Function Callgraph 选项时出现 Eclipse CDT 错误

pointers - 为什么接口(interface)不能用指针接收器实现

delphi - E2016 需要数组类型。使用 PSingle 变量

c++ - 在多态对象之外多态地调用函数

c - 当仅在中断期间读取变量时是否需要 volatile

c - 赋值时字符串指针错误?

c - 在 C : OSdev 中绘制像素

c - c编译器如何解释在同一语句中声明函数和变量?

php - Laravel:使用 Eloquent 检索父类(super class)的实例

c++ - 从子类的STL vector 到基类 vector 的转换