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唯一想到的就是做unionenum,但它似乎会有大量未使用的字段。例如:

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中进行这种伪子类化?我的目标是能够将"多个类型"传递给同一个函数,在本例中是CarBook

将公共超类作为每个子类的初始成员。

typedef struct Car {
Item item;
char *make;
} Car;
typedef struct Book {
Item item;
char *title;
char *author;
} Book;

然后,在调用泛型Item函数时,可以将Book*Car*强制转换为Item*

另一种选择是建立一个受歧视的联盟。

typedef struct Item {
// general Item stuff goes here
enum {Car, Book} type;
union {
Car car;
Book book;
};
} Item;

但如果你需要做很多这方面的工作,也许你应该使用C++而不是C,这样你就有了真正的类层次结构。

最新更新