扩展的结构 [英] Extending a structure
问题描述
typedef struct A
{
int x;
}A;
typedef struct B
{
A a;
int d;
}B;
void fn()
{
B *b;
((A*)b)->x = 10;
}
我SO看了上面的code片段。 ((A *)B) - 方式> X
不是良好的编程风格 B-> AX
好编程风格。因为任何人添加语句之前的东西A一;在结构B,它不会工作。我不明白为什么?我想这一点。有什么建议吗?
I read the above code snippet in SO. ((A*)b)->x
is not good programming style.b->a.x
is good programming style. Because anybody adds something before the statement "A a;" in structure b , it will not work. I don't understand why? I tried it too. Any suggestions please?
推荐答案
这招是用来模拟在继承C.它使可能通过地址A或B的功能它期望指向一个。
That trick is used to emulate inheritance in C. It makes possible to pass address A or B to function which expects pointer to A.
这工作,因为C保证有结构的第一个成员之前没有填充。因此,如果A是B的第一构件,在B点的开始存储器布局总是相同为A
This works because C guarantees that there is no padding before the first member of struct. So if A is first member of B, memory layout at the beginning of B is always same as A.
int doStuff(A * a) {
return a->x + 1;
}
...
B b;
doStuff((A*)&b); // Will work because b and b.a have the same start address
如果您将变动b声明:
typedef struct B
{
int d;
A a;
}B;
这将不再工作,为(A *)和b
将返回地址 BD
,而不是 BA
。
this would no longer work as (A*)&b
would return address of b.d
, not b.a
.
这篇关于扩展的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!