为什么类成员具有与其对象相同的地址? [英] Why do class members have the same address as their object?

查看:141
本文介绍了为什么类成员具有与其对象相同的地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下列情况下,每个成员都有不同的名称或实体,为什么他们的地址相同?

In the following cases, each member has a different name or entity so why are their addresses the same?

struct B { int x; };
struct A { B b; };

int main()
{
    A obj;
    cout << &obj.b.x << endl;
    cout << &obj.b << endl;
    cout << &obj << endl;
}


推荐答案

总是指向它的第一个成员(因为struct是按顺序排列的)。

Because a pointer to a struct always points to it's first member (as the struct is laid out sequentially).

In C, does a pointer to a structure always point to its first member?


(C1x§6.7.2.1.13:指向结构对象的指针,合适的是
转换,指向它的初始成员...反之亦然。可能有
是未命名的填充结构对象,但不在
开头。)

(C1x §6.7.2.1.13: "A pointer to a structure object, suitably converted, points to its initial member ... and vice versa. There may be unnamed padding within as structure object, but not at its beginning.")

注意:mange ,正确的是,如果你开始添加虚拟函数到你的结构,C + +实现这一点通过在结构的开始处的vtable t ...这使我的语句(这是真的C)不正确,当你谈到你可以可能在C ++中使用structs。

NOTE: mange points out, rightfully so, that if you start adding virtual functions to your struct, C++ implements this by tacking the vtable at the start of your struct... which makes my statement (which is true for C) incorrect when you talk about everything you could possibly do with 'structs' in C++.

这篇关于为什么类成员具有与其对象相同的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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