是否可以使用 C 来模拟继承?如何?示例代码会有帮助。
编辑:我希望继承数据和方法。仅靠集装箱船是无济于事的。可替代性 - 使用基类对象工作的任何派生类对象 - 是我所需要的。
这样做非常简单:
struct parent {
int foo;
char *bar;
};
struct child {
struct parent base;
int bar;
};
struct child derived;
derived.bar = 1;
derived.base.foo = 2;
但是如果您使用 MS 扩展(在 GCC 中使用
-fms-extensions
标志),您可以使用匿名嵌套 struct
,它看起来会好得多:
struct child {
struct parent; // anonymous nested struct
int bar;
};
struct child derived;
derived.bar = 1;
derived.foo = 2; // now it is flat
你绝对可以用(某种程度上)面向对象的风格来编写 C。
可以通过保留结构的定义来完成封装 在 .c 文件中而不是在关联的标头中。 然后外部世界通过保存指向它们的指针来处理你的对象, 并且您提供接受此类指针作为“方法”的函数 您的对象。
可以通过使用函数指针来获得类似多态的行为, 通常分为“运营结构”, 有点像 C++ 对象中的“虚拟方法表” (或者无论它叫什么)。 ops 结构还可以包括其他内容,例如 其值特定于给定“子类”的常量。 “父”结构可以保留对操作特定数据的引用 通过通用的
void*
指针。
当然,“子类”可以在多个级别上重复该模式
继承。
因此,在下面的示例中,
struct printer
类似于抽象类,
可以通过填写 pr_ops
结构来“导出”,
并提供一个包装pr_create()
的构造函数。
每个子类型都有自己的结构,该结构将被“锚定”
通过 struct printer
通用指针指向 data
对象。
fileprinter
子类型证明了这一点。
人们可以想象一台 GUI 或基于套接字的打印机,
无论代码的其余部分如何操作,都会对其进行操作
作为struct printer *
参考。
打印机.h:
struct pr_ops {
void (*printline)(void *data, const char *line);
void (*cleanup)(void *data);
};
struct printer *pr_create(const char *name, const struct output_ops *ops, void *data);
void pr_printline(struct printer *pr, const char *line);
void pr_delete(struct printer *pr);
打印机.c:
#include "printer.h"
...
struct printer {
char *name;
struct pr_ops *ops;
void *data;
}
/* constructor */
struct printer *pr_create(const char *name, const struct output_ops *ops, void *data)
{
struct printer *p = malloc(sizeof *p);
p->name = strdup(name);
p->ops = ops;
p->data = data;
}
void pr_printline(struct printer *p, const char *line)
{
char *l = malloc(strlen(line) + strlen(p->name) + 3;
sprintf(l, "%s: %s", p->name, line);
p->ops->printline(p->data, l);
}
void pr_delete(struct printer *p)
{
p->ops->cleanup(p->data);
free(p);
}
最后,fileprinter.c:
struct fileprinter {
FILE *f;
int doflush;
};
static void filepr_printline(void *data, const char *line)
{
struct fileprinter *fp = data;
fprintf(fp->f, "%s\n", line);
if(fp->doflush) fflush(fp->f);
}
struct printer *filepr_create(const char *name, FILE *f, int doflush)
{
static const struct ops = {
filepr_printline,
free,
};
struct *fp = malloc(sizeof *fp);
fp->f = f;
fp->doflush = doflush;
return pr_create(name, &ops, fp);
}
是的,您可以使用“类型双关”技术来模拟 C 中的继承。即在派生类内部声明基类(struct
),并将派生类强制转换为基类:
struct base_class {
int x;
};
struct derived_class {
struct base_class base;
int y;
}
struct derived_class2 {
struct base_class base;
int z;
}
void test() {
struct derived_class d;
struct derived_class2 d2;
d.base.x = 10;
d.y = 20;
printf("x=%i, y=%i\n", d.base.x, d.y);
}
但是,如果您想在程序中将派生类强制转换为基类,则必须在派生结构中的第一个位置声明基类:
struct base *b1, *b2;
b1 = (struct base *)&d;
b2 = (struct base *)&d2;
b1->x=10;
b2->x=20;
printf("b1 x=%i, b2 x=%i\n", b1->x, b2->x);
在此代码片段中,您只能使用基类。
我在我的项目中使用了这种技术:
oop4c