c - C中的typedef结构继承
问题描述
假设我想在 C 中创建一个类型的两个子类型。例如:
typedef struct Car {
char *make;
} Car;
typedef struct Book {
char *title;
char *author;
} Book;
这样做有哪些选择?我来自 python 背景,所以习惯于能够做类似的事情:
class Item:
pass
class Car(Item):
...
class Book(Item):
...
对于 C 来说,唯一想到的就是做 a union
orenum
但看起来它会有大量未使用的字段。例如:
typedef struct Item {
enum {Car, Book} type; // hide the class here
char *make;
char *title; // but now will have a bunch of null fields depending on `Item` type
} Item;
或者:
typedef struct Item {
union {
Car;
Book;
} item;
} Item;
在 C 中进行这种伪子类化有哪些选择?我的目标是能够将“多种类型”传递给同一个函数,在这种情况下Car
和Book
.
解决方案
将公共超类作为每个子类的初始成员。
typedef struct Car {
Item item;
char *make;
} Car;
typedef struct Book {
Item item;
char *title;
char *author;
} Book;
然后,您可以在调用泛型函数时强制转换aBook*
或Car*
to 。Item*
Item
另一种选择是有区别的工会。
typedef struct Item {
// general Item stuff goes here
enum {Car, Book} type;
union {
Car car;
Book book;
};
} Item;
但是如果你需要做很多这样的事情,也许你应该使用 C++ 而不是 C,这样你就有了真正的类层次结构。
推荐阅读
- android - 使用 ?/attr 时 actionMenuTextColor 不起作用
- css - 像 instagram 一样反应原生网格
- html - 如何在视口大小宽度中创建一个框?
- image-processing - 自动从漫画中提取图块
- segmentation-fault - 为什么我在这段代码中出现分段错误?
- python - 需要使用逗号分隔数据框列
- swift - 将对象(图钉、表情符号、形状)作为注释添加到不是地图的图像
- nginx - nginx 不提供站点地图文件
- java - 如何在 Apache Sling 的 OSGI 服务调用中判断用户的身份?
- reactjs - React Router:将 this.props.location 传递给导航栏组件