【发布时间】:2020-11-16 08:16:45
【问题描述】:
在代码中,child 被强制转换为类型 Parent,并传递给 parentMove。 child 没有成员 x 和 y。 parentMove 如何访问child.parent.x 和child.parent.y?类型转换如何在这里工作?谢谢
#include <stdio.h>
typedef struct{
int x, y;
int (*move)();
}Parent;
typedef struct {
Parent parent;
int h, w;
}Child;
int parentMove(Parent* parent, int y, int x){
parent->y+=y;
parent->x+=x;
printf("%d %d", parent->y, parent->x);
return 1;
}
int main(void) {
Parent parent = {.x = 2, .y = 1, .move = &parentMove};
Child child = {.parent = parent, .h = 3, .w = 4};
((Parent*)(&child))->move((Parent*)&child, 10, 10);
return 0;
}
【问题讨论】:
-
见Is pointer to struct a pointer to its first member?。
&child == &child.parent,后者是Parent *,这就是演员阵容起作用的原因。 -
int (*move)();应该是int (*move)(Parent* parent, int y, int x);,是不是故意省略了? -
@csavvy 我知道它有效,所以我故意省略了它。不过这是个坏习惯
-
@Austin AFIK 那是 UB。所以它不起作用。它只是表现得像它一样。
标签: c inheritance