1. 程式人生 > >C++中的虛表(vtable)和虛指標(vptr)示例詳解

C++中的虛表(vtable)和虛指標(vptr)示例詳解

1、每個有virtual函式的c++類都有一個vtable,每個類物件都有個vtable的vptr; 2、在vc中,類的繼承是在基類後面追加資料的形式進行繼承的。

測試程式碼如下(在32位系統下的vs2008環境中測試的):

class Test { public:Test(int a) {data = a;}virtual ~Test() {cout<<“Test deconstruct”<<endl;}//基類中的虛解構函式virtual void fun11() {cout<<“Test virtual fun11”<<endl;}//基類中的虛擬函式fun11virtual void fun12() {cout<<“Test virtual fun12”<<endl;}//基類中的虛擬函式fun12int data; }; class Test1:public Test { public:Test1(int d1, int d2):Test(d2) {data1 = d1;data2 = d2;} int data1; int data2;virtual ~Test1() {cout<<“test1 deconstruct”<<endl;}//派生類中的虛解構函式virtual void fun1() {cout<<“test1 virtual fun1”<<endl;}//派生類中的虛擬函式fun1,不是實現基類中的fun11的多型virtual void fun2() {cout<<“test1 virtual fun2”<<endl;}//派生類中的虛擬函式fun2,不是實現基類中的fun12的多型 };

typedef void (Fun)(void);//指向函式的指標 int main() {cout<<“test in 32bit system”<<endl;Test1 obj(1,2);//定義物件obj cout << "obj’s Size = " << sizeof(obj) << endl; cout << "obj 's Address = " << &obj << endl; cout<<"second Test1 object’s address = "<<&obj + 1<<endl;//為了測試(int

)(&obj+1)和((int*)&obj+1)的區別 cout<<“third Test1 object’s address = “<<&obj + 2<<endl; cout<<“base data address and data: “<<(int*)&obj + 1<<”\t”<<((int)&obj + 1)<<endl; cout<<“derivate data1 address and data1:”<<(int*)&obj + 2<<”\t”<<((int
)&obj + 2)<<endl; cout<<“derivate data2 address and data2:”<<(int*)&obj + 3<<"\t"<<((int)&obj + 3)<<endl;

//獲得虛表指標,顯示虛表中的內容 cout<<“vtable address = “<<(int*)&obj<<”\t”<<"value = "<<((int)&obj + 0)<<endl; cout<<"vtable value0 = "<<((int)(int)((int*)&obj+0)+0)<<endl; cout<<"vtable value1 = "<<((int)(int)((int*)&obj+0)+1)<<endl; cout<<"vtable value2 = "<<((int)(int)((int*)&obj+0)+2)<<endl; cout<<"vtable value3 = "<<((int)(int)((int*)&obj+0)+3)<<endl; cout<<"vtable value4 = "<<((int)(int)((int*)&obj+0)+4)<<endl; cout<<"vtable value5 = "<<((int)(int)((int*)&obj+0)+5)<<endl; Fun pFun = NULL; pFun = (Fun)((int)(int)((int*)&obj+0)+1); pFun(); pFun = (Fun)((int)(int)((int*)&obj+0)+2); pFun(); pFun = (Fun)((int)(int)((int*)&obj+0)+3); pFun(); pFun = (Fun)((int)(int)((int*)&obj+0)+4); pFun(); return 0; } 版權宣告:本文為博主原創文章,未經博主允許不得轉載。 https://mp.csdn.net/mdeditor/83016474