【发布时间】:2014-03-04 02:42:37
【问题描述】:
我有一些这样的代码:
#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;
}
我在 code::blocks(version13.12) 中运行这些代码,但它打印“~base1”,我不知道为什么它不打印“father.f()”。我认为 v 点到grand虚拟表的地址,所以当我将v转换为base并调用f函数时,然后b调用虚拟表中的第一个虚拟函数。
我不知道我是对还是错,你能告诉我吗。谢谢大家!
【问题讨论】:
标签: c++ void-pointers