gpt4 book ai didi

c++ - 为什么类成员的地址与其对象相同?

转载 作者:太空宇宙 更新时间:2023-11-04 12:56:41 24 4
gpt4 key购买 nike

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

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

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

最佳答案

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

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

(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 来实现这一点...这使我的声明(这对 C 来说是正确的)当你谈论你可以用 C++ 中的“结构”做的所有事情时,这是不正确的。

关于c++ - 为什么类成员的地址与其对象相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46221888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com