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; }
從輸出結果咱們能夠看出,咱們能夠直接獲取到虛函數表以及表中每個函數的地址。以下圖所示: