我如何可以模拟用C OO风格多态性? [英] How can I simulate OO-style polymorphism in C?
问题描述
有没有写在 C
编程语言OO般code的方法吗?
Is there a way to write OO-like code in the C
programming language?
另请参阅:
- http://stackoverflow.com/questions/351733/can-you-write-object-oriented-$c$c-in-c
- http://stackoverflow.com/questions/415452/object-orientation-in-c
通过在[C] OO搜索找到。
Found by searching on "[c] oo".
推荐答案
第一个C ++编译器(带类的C)实际上会生成C code,所以这是绝对可行的。
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->调用(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屋!