根据我在面向对象 C 编程方面的经验,我看到了两种实现派生类的方法。
第一种方法,将父类定义为.h 文件。然后从这个类派生的每个类都会做:
文件 parent_class.h:
int member1;
int member2;
文件testing.c:
struct parent_class {
#include "parent_class.h" // must be first in the struct
}
struct my_derived_class {
#include "parent_class.h" // must be first in the struct
int member3;
int member4;
}
第二种方法,会做:
文件testing.c:
struct parent_class {
int member3;
int member4;
}
struct my_derived_class {
struct parent_class; // must be first in the struct
int member3;
int member4;
}
您最喜欢用 C 编写派生类的方法是什么(不一定是我做过的)?为什么?
您更喜欢哪种方法,第一种方法还是第二种方法(或您自己的方法)?
最佳答案
我是使用方法 2 的库的维护者之一。与方法 1 一样有效,但没有任何预处理器技巧。或者它实际上工作得更好,因为您可以拥有将基类作为参数的函数,并且您可以只转换为基结构,C 保证这对第一个成员有效。
比较有意思的问题是,你是怎么做虚函数的?在我们的例子中,结构有指向所有函数的指针,并且初始化设置了它们。它稍微简单一些,但比使用指向共享 vtable 的指针的“正确方法”有更多的空间开销。
无论如何,我更愿意使用 C++ 而不是将其与纯 C 混用,但是政治..
关于c - C 中的派生类 - 你最喜欢的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/660083/