C中的结构继承

Sid*_*qui 3 c c++

是否可以在标准C或C++中继承另一个结构?

Mar*_*rst 13

您可以在另一个内部嵌入一个结构来模拟C中的继承:

typedef struct {
    int i;
} base;

void basefunc(base *b);

typedef struct {
    base b;
    char c;
} extended;

extended e;
/* Initialise extended here */
basefunc(&e.b);      /* Use the type checker */
basefunc((base*)&e); /* Just make sure you know what you're doing */
Run Code Online (Sandbox Code Playgroud)

  • 或者,因为保证指向结构的指针也指向它的第一个成员,你可以将其强制转换 - "basefunc((base*)e)" (3认同)

Jam*_*lis 10

C不支持继承.

C++确实支持继承.

  • @Arman:好的.Stack Overflow有[一本优秀的初学C++书籍清单](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)和[一本优秀的初学者C书籍清单]( http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list).任何这些初学者书都会包含这些信息. (3认同)