首页 > 解决方案 > 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 unionorenum但看起来它会有大量未使用的字段。例如:

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.

标签: c

解决方案


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

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,这样你就有了真正的类层次结构。


推荐阅读