1、带有虚函数的对象内存布局ios
#include <iostream> using namespace std; class Test { public: virtual void f(){cout << "Func:f()" << endl;}; public: int a; }; int main() { cout << sizeof(Test) << endl; //输出:8 Test test; cout << &test << "\t" << &test.a << endl;//输出:0xbf91e508 0xbf91e50c return 0; }
在上面的例子中,咱们定义了一个简单的包含一个虚函数的类。从输出咱们能够看出两点:
#include <iostream> using namespace std; class Test { public: virtual void f(){cout << "Func:f()" << endl;}; virtual void g(){cout << "Func:g()" << endl;}; virtual void h(){cout << "Func:h()" << endl;}; private: int a; }; int main() { Test test; typedef void (*Func)(void);//定义个函数指针宏 cout << "vptbl address:" << (int *)(&test) << endl;//输出:vptbl address:0xbfc85494 cout << "func1 address:" << (int *)*(int *)(&test) << endl;//输出:func1 address:0x8048988 Func pFunc = (Func)*((int *)*(int *)(&test)); pFunc();//输出:Func:f() pFunc = (Func)*((int *)*(int *)(&test)+1); pFunc();//输出:Func:g() pFunc = (Func)*((int *)*(int *)(&test)+2); pFunc();//输出:Func:h() return 0; }
从输出结果咱们能够看出,咱们能够直接获取到虚函数表以及表中每个函数的地址。以下图所示: