C++ void*转换为基类并调用虚函数

C++ void*转换为基类并调用虚函数,c++,void-pointers,C++,Void Pointers,我有一些这样的代码: #include <iostream> using namespace std; //base class class Base { public: Base(){} virtual void f() { cout<<"father.f()"<<endl; } virtual ~Base(){} }; //a empty c

我有一些这样的代码:

#include <iostream>

using namespace std;
//base class
class Base
{
    public:
        Base(){}

        virtual void f()
        {
            cout<<"father.f()"<<endl;
        }
        virtual ~Base(){}
};
//a empty class
class Base1
{
    public:
        Base1(){}
        virtual ~Base1()
        {
            cout<<"~base1"<<endl;
        }
};
//the child class of the base class
class Child :public Base
{
    public:
        Child(){}
        virtual ~Child(){}
};
//the grandchild class of the base class,and child class of the base1 class
class Grand :public Base1,public Child
{
    public:
        Grand(){}
        virtual ~Grand(){}
        //overwrite base's f()
        void f()
        {
            cout<<"grand.f"<<endl;
        }
};
int main()
{
    void *v = new Grand();
    Base *b = (Base*)(v);
    //i think it print "father.f()",but it print"~base1"
    b->f();
    return 0;
}
#包括
使用名称空间std;
//基类
阶级基础
{
公众:
Base(){}
虚空f()
{

cout因为使用多重继承时,如果不经过子类,就不能直接向上层类强制转换。这是因为
void*
在内存中不包含任何关于构成最终
Grand*
实例的各种类的布局的信息

要解决此问题,您确实需要将其强制转换为其运行时类型:

Base *b = (Base*)(Grand*)v;
b->f();
想想布局可能在不同的位置有
Base
,想想另一个

class Grand2 : public Something, public Else, public Base1, public Child {
  ..
}

现在,
Base
位于
Grand2
结构中的什么位置?与
Grand
不同。编译器如何知道从指向非指定类的指针开始的正确偏移量(可以是
Grand
Grand2
)?

或者,类似地,在转换为
void*
之前转换为
Base*
。谢谢,但我不明白为什么b-f()调用~base1()。你能告诉我为什么吗?