标签:
1 #include <iostream> 2 3 using namespace std; 4 5 class father 6 { 7 public: 8 father(int x):m_idata(x) 9 {} 10 11 virtual void show(int idata) 12 { 13 cout << "papa" << endl; 14 cout << idata-20 << endl; 15 } 16 virtual ~father(){} 17 18 private: 19 int m_idata; 20 }; 21 22 class child:public father 23 { 24 public: 25 child(int x, int y):father(x),m_ichild_data(y) 26 { 27 } 28 29 virtual void show(int idata) 30 { 31 cout << "wawa" << endl; 32 cout << idata << endl; 33 //cout << m_ichild_data << endl; 通过虚函数表直接调用,无法访问成员变量,没有对应到对象上 34 } 35 36 virtual ~child(){} 37 private: 38 int m_ichild_data; 39 40 }; 41 42 typedef void (* FUNC)(int); 43 44 int main() 45 { 46 father fa(9); 47 cout << "object address is vptr address: " << &fa << endl; 48 cout << "111 vtable address: " << *(int *)(&fa) << endl; //suppose pointer is 4 bytes ,value of vptr 49 cout << "func show address: " << *(int *)(*(int *)(&fa)) << endl; 50 int x=66; 51 //firstchild.show(x); 52 //FUNC func = ( void (*)(void) )(*(int *)(*(int *)(&firstchild)) ); 53 FUNC func3 = ( FUNC )(*(int *)(*(int *)(&fa) )); 54 func3(x); 55 56 child firstchild(88,3456); 57 cout << "------------first child-------------" << endl; 58 cout << "object address is vptr address: " << &firstchild << endl; 59 cout << "vtable address: " << *(int *)(&firstchild) << endl; //suppose pointer is 4 bytes ,value of vptr 60 cout << "func show address: " << *(int *)(*(int *)(&firstchild)) << endl; 61 //int x=66; 62 //firstchild.show(x); 63 //FUNC func = ( void (*)(void) )(*(int *)(*(int *)(&firstchild)) ); 64 FUNC func = ( FUNC )(*(int *)(*(int *)(&firstchild)) ); 65 func(x); //没有this指针 无法显示数据成员 66 67 cout << "first data member: " << *(int *)((int *)(&firstchild)+1) << endl; 68 69 cout << endl << "-------------second child--------------" << endl; 70 child secondchild(888,222); 71 cout << "object address is vptr address: " << &secondchild << endl; 72 cout << "value of vptr: " << *(int *)(&secondchild) << endl; //suppose pointer is 4 bytes 73 cout << "func show address: " << *(int *)(*(int *)(&secondchild)) << endl; 74 75 FUNC func2 = ( FUNC )(*(int *)(*(int *)(&secondchild)) ); 76 func2(x); //没有this指针 无法显示数据成员 77 78 return 0; 79 }
1 每个类对应一个虚函数表,不同对象的第一个slot都是相同值,即该表的地址。
2 从地址看7c和88之间只有12个字节,应该是x和func3被优化掉了。
3 inside c++ object model说虚表里第一个是type_info,是否是指最后一个?
标签:
原文地址:http://www.cnblogs.com/lijinping/p/5884418.html