半继承在C:请问这个片段的工作? [英] Semi-inheritance in C: How does this snippet work?

查看:135
本文介绍了半继承在C:请问这个片段的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

破解多态性在C有限形式的一种方法是做这样的事情:

One way to hack limited form of polymorphism in C is to do something like this:

typedef struct {
    int x;
} base;

typedef struct {
    base super;
    int y;
} derived;

现在你可以参考派生实例作为基本实例,这取决于变量是如何投,即:

Now you can refer to a derived instance as a base instance, depending on how the variable is cast, ie:

derived my_derived;
my_derived.y = 10;
my_derived.super.x = 20;
//will print 10
printf("%d", (&my_derived)->y);
//will print 20
printf("%d", ((base*)(&my_derived) )->x);

所以我的问题是,究竟是如何工作的呢?是不是因为当你将它转换为基础,参考一变,你引用INT成员'X'来自'基地'结构的开始偏移?这是我能想到的唯一的事情,任何帮助将是AP preciated。

So my question is, how exactly does this work? Is it because when you cast it as base and referencing a variable, you're referencing the int member 'x' as the offset from the start of the 'base' struct? This is the only thing I can think of, any help would be appreciated.

非常感谢!

推荐答案

在一个结构,可以有数据元素之间或在结构的最后无名填充字节,而不是开头。因此,结构类型的对象的第一个数据元素的地址被保证是一样的结构类型对象本身的地址。

In a struct, there can be unnamed padding bytes between data elements or at the end of the struct, but not at the beginning. So, the address of the first data element of a struct-type object is guaranteed to be the same as the address of the struct-type object itself.

所以,在你的榜样, my_derived 的地址是一样的 my_derived.super 的地址。

So, in your example, the address of my_derived is the same as the address of my_derived.super.

这篇关于半继承在C:请问这个片段的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆