c++ 对象模型(二)

来源:互联网 发布:seo自学好学吗 编辑:程序博客网 时间:2024/05/20 20:58

《c++ 对象模型》讲到了,对于虚函数表指针的分布,直接截书中的图

先上代码

struct no_virts{int d1;int d2;};class has_virts : public no_virts{public:int d3;virtual void foo() { printf("--- has_virts foo \n"); } };void testMemObj(){has_virts hv;hv.d1 = 111;hv.d2 = 222;hv.d3 = 333;//无论虚函数放在对象的哪个位置,对象中的虚函数表都是位于对象内存分布的顶端Fun pFunc = (Fun)*((int*)(*((int*)(&hv) + 0)) + 0); //foo方法 pFunc();int d1 = (int)*((int*)(&hv) + 1); //111printf("--- d1:%d\n", d1);int d2 = (int)*((int*)(&hv) + 2); //222printf("--- d2:%d\n", d2);int d3 = (int)*((int*)(&hv) + 3); //333printf("--- d3:%d\n", d3);}




0 0
原创粉丝点击