当通过基指针访问时,编译器如何确定成员的位置

Let*_*_Be 5 c++

这只是跳进了我的脑海,我无法弄明白.

如果我有这样的代码:

struct A { char x[100]; };

struct B { int data; };

struct C : A, B {};

#include <iostream>
using namespace std;

B* get_me_some_stuff()
{
        static int x = 0;
        if (++x % 2 == 0)
                return new B();
        else
                return new C();
}

int main()
{
        B* x = get_me_some_stuff();
        B* y = get_me_some_stuff();

        x->data = 10;
        y->data = 20;

        cout << x->data << " " << y->data << endl;

        return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译器如何确定data成员的内存位置?

kwa*_*ord 2

尝试这个:

C* x = new C();
B* y = x;
cout << x << " " << y << endl;
Run Code Online (Sandbox Code Playgroud)

对我来说输出:

0x1ae2010 0x1ae2074
Run Code Online (Sandbox Code Playgroud)

C*从to B*(或向另一个方向)进行转换的行为包括必要的指针算术。