C++ 多重继承和 void* 交叉委托?

C++ multiple inheritance and cross delegation with void*?

class Base1
{
public:
    virtual ~Base1(){}

    virtual void whatever()
    {
        cout << "whatever" << endl;
    }
};

class Base2
{
public:
    virtual ~Base2(){}

    virtual void aFunc(int i) = 0;
};

class A : public Base1, public Base2
{
public:
    A()
    {}
    ~A()
    {}

    virtual void aFunc(int i) final
    {
        cout << "func" << endl;
    }
};

int main()
{
    void* a;
    a = new A();

    (static_cast<Base2*>(a))->aFunc(0);

    Base2* ptr = static_cast<Base2*>(a);
    ptr->aFunc(0);

    return 0;
}

这个例子打印出 "whatever" 而不是 "func",如果我将带有 void* 的行更改为 A* 而它打印出 "func"。这是已知行为吗?我希望是这样,只是不知道为什么。

Is this a known behavior?

是的。如果您转换为 void* 然后返回相同类型,则行为定义明确。如果你转换回不同的类型,它是未定义的。

I would expect that's the case just don't know why.

不能保证基础子对象与完整对象具有相同的地址;实际上,如果有多个非空基 class,则至少有一个子对象必须位于不同的地址。因此,从 A*Base2* 的有效转换可能需要调整指针的值,而不仅仅是将其重新解释为不同的类型。转换为 void* 并返回无法进行该调整。