繁体   English   中英

C 中的 typedef 结构 inheritance

[英]typedef struct inheritance in C

假设我想在 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 中有哪些选项可以进行这种伪子类化? 我的目标是能够将“多种类型”传递给同一个 function,在本例中为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,所以你有真正的 class 层次结构。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM