我实现了一个简单的测试来检查派生类的内存等级,所以我发现派生类的虚拟表中有两个虚拟析构函数地址。有人可以向我解释吗?
代码:
#include<iostream>
#include<ostream>
#include<cstdio>
using namespace std;
class Base1
{
public:
Base1():a(1){}
virtual ~Base1()
{
cout << "~Base1" << endl;
}
int a;
virtual void print()
{
cout << "I am base 1!" << endl;
}
};
class Base2
{
public:
Base2():b(2){}
virtual ~Base2(){
cout << "~Base2" << endl;
}
int b;
virtual void print()
{
cout << "I am base 2!" << endl;
}
};
class Derive : public Base1, public Base2
{
public:
Derive():c(3){}
virtual ~Derive(){
cout << "~Derive" << endl;
}
int c;
virtual void print()
{
cout << "I am Derive!!" << endl;
}
void prints()
{
cout << "I am not virtual!!" << endl;
}
};
int main()
{
typedef void (*Func) (void);
Derive *d = new Derive();
int **p = (int **)(d);
Func f = (Func)(p[0][0]);
//int s = (int)(*(p + 3));
Func f2 = (Func)(p[0][1]);
//cout << p << endl;
//cout << s << endl;
f();
//cout.flush();
f2();
//f();
return 0;
}
我发现
f() and f2()
结果如下:</p>
~Derive
~Base2
~Base1
~Derive
~Base2
~Base1
是派生类的析构函数。为什么有两个?
还有一个问题:非虚成员函数的地址在哪里?我发现派生类的内存中不存在非虚函数地址。它在哪里?