C++中的涉及到虚表时,类对象的布局分为:虚表与数据成员,子类包含派生类布局,假设下面一个程序:
#include <iostream> using namespace std; class B {
private:
int a;
public:
B() {
a = ;
} virtual void fun() {
cout << "B::fun" << endl;
}
}; class A:public B {
public:
A() {
cout << "class A constructor" << endl;
m = ;
n = ;
} ~A() {
cout << "~A()" << endl;
}
virtual void fun() {
cout << "A::fun" << endl;
} private:
int m,n;
}; int main(int argc, char *argv[])
{
A a;
int *p;
int **pvtr = (int **)&a; typedef void (*pf_t)(); pf_t pf;
p = static_cast<int *>((int *)&a); pf = (pf_t)(pvtr[][]);
pf();
//cout << "*pf:" << *pf << ",pf:" << pf << endl; //(*(*pf+sizeof(void*) * 2))(); cout << "p:" << *p << endl;
p ++ ;
cout << "p:" << *p << endl;
p++;
cout << "p:" << *p << endl;
p++;
cout << "p:" << *p << endl; p++;
cout << "p:" << *p << endl; return ;
}
通过VS 2010显示对象布局图(cl -d1reportAllClassLayout),其中meta为对应对象的类型信息:
类B:
class B size():
+---
| {vfptr}
| a
+--- B::$vftable@:
| &B_meta
|
| &B::fun
类A:
class A size():
+---
| +--- (base class B)
| | {vfptr}
| | a
| +---
| m
| n
+--- A::$vftable@:
| &A_meta
|
| &A::fun A::fun this adjustor: