有没有办法用C
编程语言编写类似OO的代码?
另请参阅:
通过搜索"[c]oo"找到.
有没有办法用C
编程语言编写类似OO的代码?
另请参阅:
通过搜索"[c]oo"找到.
第一个C++编译器("C类")实际上会生成C代码,所以这是可行的.
基本上,你的基类是一个 struct ;派生 struct 必须在第一个位置包含基 struct ,因此指向"派生" struct 的指针也将是指向基 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
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.