怎么用c写虚函数?

How to write virtual function in c?

为了遵循准备好的设计文档,我想在 C 中创建虚函数。有什么最佳实践吗? 正如@imreal 建议的那样,我们可以使用函数指针来转换 C 结构,其工作方式类似于 C++ classes,但我们如何才能确保虚拟基 class 函数覆盖派生的 class 函数。

在我的例子中,我需要这个特性来遵循文档,但我认为它在我们将 C++ 代码转换为 C 时也很有用。这在将 C++ 代码与 C 代码组合时是必需的。

不,你不能。 'virtual' 不是 C 词汇表的一部分,'access level'

也不是

该语言并未将其作为一项功能提供,但您可以实现相同的功能。

创建一个带有函数指针的结构:

typedef struct Base Base_t;
struct Base {
    void (*f1)(Base_t* self);
    void (*f2)(Base_t* self);

    int dat1;
    int dat2;
};

编写一个函数作为构造函数,为这些指针分配不同的函数。

Base constructor1()
{
    Base l = {func1, func2, 0, 0};
    return l;
}

Base constructor2()
{
    Base l = {func3, func4, 6, 13};
    return l;
}

调用方法:

Base a = constructor1();
a.f1(&a);

每个函数都需要一个 self/this 指针来访问数据成员。

实例:

http://ideone.com/LPSd65

在 C 语言中没有 'virtual' 函数这样的概念。

相反,我建议您看看我的

基本面:

  • 定义一个struct
  • 提供一套函数来作用于 struct
  • 如果特定用途需要不同的功能,则调用不同的功能

没有内置语言支持,但如果缺少特殊实现,您可以获得与使用默认实现相同的一般功能。可能是这样的:

#include <stdio.h>

struct animal {
    const char *name;
    void (*move)(struct animal *);
};

void fly(struct animal *a)
{
    printf("soaring %s\n", a->name);
}

void walk(struct animal *a)
{
    printf("walk %s, walk\n", a->name);
}

void animal_move(struct animal *a)
{
    void (*move)(struct animal *) = a->move ? : walk;
    move(a);
}

int main(void)
{
    struct animal elephant = { .name = "elephant" };
    struct animal bird = { .name = "bird", .move = fly };

    animal_move(&elephant);
    animal_move(&bird);
    return 0;
}