【发布时间】:2014-11-10 10:20:05
【问题描述】:
扩展 stuct 的典型 C99 方式类似于
struct Base {
int x;
/* ... */
};
struct Derived {
struct Base base_part;
int y;
/* ... */
};
然后我们可以将struct Derived *的实例转换为struct Base *,然后访问x。
我想直接访问struct Derived * obj; 的基本元素,例如obj->x 和obj->y。 C11 提供扩展结构,但正如 here 所解释的,我们只能将此功能与匿名定义一起使用。那怎么写呢
#define BASE_BODY { \
int x; \
}
struct Base BASE_BODY;
struct Derived {
struct BASE_BODY;
int y;
};
然后我可以访问与 Derived 的一部分相同的 Base 成员,而无需任何强制转换或中间成员。如果需要,我可以将 Derived 指针转换为 Base 指针。
这可以接受吗?有什么陷阱吗?
【问题讨论】:
-
作为替代方案,您可以考虑通过
gcc或clang中的-fms-extensions选项使用typedef(请参阅this 答案),但它是非标准的。
标签: c macros struct coding-style c11