如何在 C 中模拟 OO 风格的多态性? [英] How can I simulate OO-style polymorphism in C?
问题描述
有没有办法用 C
编程语言编写类似 OO 的代码?
Is there a way to write OO-like code in the C
programming language?
另见:
通过搜索[c] oo"找到.
Found by searching on "[c] oo".
推荐答案
第一个 C++ 编译器(C with classes")实际上会生成 C 代码,所以这绝对是可行的.
The first C++ compiler ("C with classes") would actually generate C code, so that's definitely doable.
基本上,你的基类是一个结构体;派生结构必须在第一个位置包含基结构,这样指向派生"结构的指针也将是指向基结构的有效指针.
Basically, your base class is a struct; derived structs must include the base struct at the first position, so that a pointer to the "derived" struct will also be a valid pointer to the base struct.
typedef struct {
data member_x;
} base;
typedef struct {
struct base;
data member_y;
} derived;
void function_on_base(struct base * a); // here I can pass both pointers to derived and to base
void function_on_derived(struct derived * b); // here I must pass a pointer to the derived class
函数可以作为函数指针作为结构的一部分,因此像 p->call(p) 这样的语法成为可能,但您仍然必须显式地将指向结构的指针传递给函数本身.
The functions can be part of the structure as function pointers, so that a syntax like p->call(p) becomes possible, but you still have to explicitly pass a pointer to the struct to the function itself.
这篇关于如何在 C 中模拟 OO 风格的多态性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!