如何使用 C 对继承进行建模? [英] How can Inheritance be modelled using C?
本文介绍了如何使用 C 对继承进行建模?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用 C 对继承进行建模?如何?示例代码会有所帮助.
Is it possible to model inheritance using C? How? Sample code will help.
我希望继承数据和方法.仅靠集装箱船是无济于事的.可替代性——使用任何基类对象可以工作的派生类对象——正是我所需要的.
I am looking to inherit both data and methods. Containership alone will not help. Substitutability - using any derived class object where a base class object works - is what I need.
推荐答案
这样做很简单:
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
s,它看起来会更好:
But if you use MS extension (in GCC use -fms-extensions
flag) you can use anonymous nested struct
s and it will look much better:
struct child {
struct parent; // anonymous nested struct
int bar;
};
struct child derived;
derived.bar = 1;
derived.foo = 2; // now it is flat
这篇关于如何使用 C 对继承进行建模?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文