如何在C中实现C ++虚函数

C ++语言提供virtualfunction。 在纯C语言实现的约束下,如何实现类似的效果?

从这里偷来了 。

来自C ++类

 class A { protected: int a; public: A() {a = 10;} virtual void update() {a++;} int access() {update(); return a;} }; 

可以导出C代码片段。 class A的三个C ++成员函数使用外联(独立)代码重写,并通过地址收集到名为A_functable的结构中。 A的数据成员与函数表结合成一个名为A的C结构。

 struct A; typedef struct { void (*A)(struct A*); void (*update)(struct A*); int (*access)(struct A*); } A_functable; typedef struct A{ int a; A_functable *vmt; } A; void A_A(A *this); void A_update(A* this); int A_access(A* this); A_functable A_vmt = {A_A, A_update, A_access}; void A_A(A *this) {this->vmt = &A_vmt; this->a = 10;} void A_update(A* this) {this->a++;} int A_access(A* this) {this->vmt->update(this); return this->a;} /* class B: public A { public: void update() {a--;} }; */ struct B; typedef struct { void (*B)(struct B*); void (*update)(struct B*); int (*access)(struct A*); } B_functable; typedef struct B { A inherited; } B; void B_B(B *this); void B_update(B* this); B_functable B_vmt = {B_B, B_update, A_access}; void B_B(B *this) {A_A(this); this->inherited.vmt = &B_vmt; } void B_update(B* this) {this->inherited.a--;} int B_access(B* this) {this->inherited.vmt->update(this); return this->inherited.a;} int main() { A x; B y; A_A(&x); B_B(&y); printf("%d\n", x.vmt->access(&x)); printf("%d\n", y.inherited.vmt->access(&y)); } 

比必要的更精细,但它得到了重点。

@GCC ….虚函数在对象的Base类中声明,然后“覆盖”或在子类中实现。 也就是说,你有车辆基类,你创建了两个子类,摩托车和汽车。 Base类将声明AddTires()的虚函数然后Sub Classes将实现此函数,每个子类将以不同方式实现它。 一辆汽车有4个轮子,摩托车有2个。但是我不能给你C或C ++的语法。 希望这可以帮助

虚函数是C ++面向对象的一个​​特性。 它们指的是依赖于特定对象实例的方法,而不是您当前携带它们的类型。

换句话说:如果将对象实例化为Bar,然后将其强制转换为Foo,则虚拟方法仍然是实例化的(在Bar中定义),而其他方法将来自Foo。

虚函数通常通过vtable实现(这是为了你做更多的研究;))。

您可以使用结构作为穷人的对象并在其中保存函数指针来模拟C中的类似事物。

(更准确地说,非虚函数使得该方法应该取自哪个类是模糊的,但实际上我相信C ++使用当前类型。)

以下是虚拟function的描述。

没有办法在普通的C中实现虚函数,因为C没有inheritance的概念。

更新:正如下面的评论中所讨论的,可以使用结构和函数指针在直接C中执行类似于虚函数的操作。 但是,如果您习惯使用具有“真实”虚函数的C ++语言,您可能会发现C近似不那么优雅且难以使用。