[英]typedef struct inheritance in C
Let's say I want to create two sub-types of a type in C. For example:假设我想在 C 中创建一个类型的两个子类型。例如:
typedef struct Car {
char *make;
} Car;
typedef struct Book {
char *title;
char *author;
} Book;
What are the options for doing this?这样做有哪些选择? I come from a python background, so am used to being able to do something like:我来自 python 背景,所以习惯于能够做类似的事情:
class Item:
pass
class Car(Item):
...
class Book(Item):
...
The only thing that comes to mind for C is doing a union
or enum
but then it seems like it will have a ton of un-used fields.对于 C,唯一想到的是做一个union
或enum
,但它似乎会有大量未使用的字段。 For example:例如:
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;
Or:要么:
typedef struct Item {
union {
Car;
Book;
} item;
} Item;
What options are there to do this sort of pseudo-subclassing in C?在 C 中有哪些选项可以进行这种伪子类化? My goal here is to be able to pass 'multiple types' to the same function, in this case Car
and Book
.我的目标是能够将“多种类型”传递给同一个 function,在本例中为Car
和Book
。
Put the common superclass as an initial member of each subclass.将公共超类作为每个子类的初始成员。
typedef struct Car {
Item item;
char *make;
} Car;
typedef struct Book {
Item item;
char *title;
char *author;
} Book;
You can then cast a Book*
or Car*
to Item*
when calling generic Item
functions.然后,您可以在调用通用Item
函数时将Book*
或Car*
转换为Item*
。
Another option is a discriminated union.另一种选择是受歧视的工会。
typedef struct Item {
// general Item stuff goes here
enum {Car, Book} type;
union {
Car car;
Book book;
};
} Item;
But if you need to do a lot of this, maybe you should use C++ instead of C, so you have real class hierarchies.但是如果你需要做很多这样的事情,也许你应该使用 C++ 而不是 C,所以你有真正的 class 层次结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.