网站建设工具的公司,电子商务网站建设的背景,苏州知名网站建设定制,前端用户中心 wordpress2019独角兽企业重金招聘Python工程师标准 虚函数是C实现多态的关键#xff0c;没有虚函数#xff0c;C只能是OB#xff0c;不能完成OO。 本文介绍的是没有继承情况下#xff0c;带有虚函数的类在内存中布局#xff0c;以及其实例#xff08;对象#xff0… 2019独角兽企业重金招聘Python工程师标准 虚函数是C实现多态的关键没有虚函数C只能是OB不能完成OO。 本文介绍的是没有继承情况下带有虚函数的类在内存中布局以及其实例对象内存布局。 1.源码 view plain #include iostream #include stdio.h using namespace std; class CVirtual { public: int x; public: virtual void VF() { coutthis-xendl; couthelloendl; } public: CVirtual(int x) { this-x x; } }; typedef void (CVirtual::*Fun)(); union { Fun f; unsigned int addr; }ut; int main(int argc, char** argv) { //打印出类实例的大小 cout对象大小为 :sizeof(CVirtual)endl; CVirtual *p new CVirtual(999); CVirtual *p1 new CVirtual(888); //打印对象地址 cout新建对象的地址 :pendl; //打印第一个成员变量地址 cout对象中第一个成员变量的地址 :p-xendl; //打印虚函数的地址 ut.f (CVirtual::VF); cout类中第一个虚函数的地址 :std::hexstd::showbaseut.addrendl; //虚表指针 unsigned int vptr *((unsigned int*)p); cout对象1中虚表指针(即虚表地址)为 :std::hexstd::showbasevptrendl; //虚表第一项值为 unsigned slot0 *((unsigned int*)vptr); cout虚表中第一项的值(第一个虚函数地址):std::hexstd::showbaseslot0endl; //虚表指针 unsigned int vptr1 *((unsigned int*)p1); cout对象2中虚表指针(即虚表地址)为 :std::hexstd::showbasevptr1endl; //虚表第一项值为 unsigned slot01 *((unsigned int*)vptr1); cout虚表中第一项的值(第一个虚函数地址):std::hexstd::showbaseslot01endl; //虚函数的原型 typedef void (__thiscall *MyFun)(void* pThis); //调用虚函数表中的第一个函数 MyFun f (MyFun)slot0; f(p); //调用虚函数 MyFun f1 (MyFun)ut.addr; f1(p); delete p; delete p1; cinargc; } 2.结果 3.内存布局图 4.结论 虚函数表在编译期间已经确定建立在data区运行期只是把由构造函数把对象的vptr值设定为这个地址同一个类的所有实例共享同一个虚函数表虚函数表中的每一个项目不一定是虚函数的地址很可能是一个代理函数然后由代理函数再调用虚函数 转载于:https://my.oschina.net/kaixindewo/blog/28519