首页 > 编程 > C++ > 正文

C++对象内存布局-单一继承

2019-11-08 18:34:37
字体:
来源:转载
供稿:网友

看《深度探索C++对象模型》有点力不从心。 找到了一篇博客写的很好,把代码跑了一篇,加深了理解 原博客:http://blog.csdn.net/haoel/article/details/3081328

内存分布规则:

虚函数表在最前面的位置。成员变量根据其继承和声明顺序依次放在后面。在单一的继承中,被重写的虚函数在虚函数表中得到了更新。

来看实例:

这里写图片描述 代码:

#include<iostream>using namespace std;class Parent {public: int iparent; Parent() :iparent(10) {} virtual void f() { cout << " Parent::f()" << endl; } virtual void g() { cout << " Parent::g()" << endl; } virtual void h() { cout << " Parent::h()" << endl; }};class Child : public Parent {public: int ichild; Child() :ichild(100) {} virtual void f() { cout << "Child::f()" << endl; } virtual void g_child() { cout << "Child::g_child()" << endl; } virtual void h_child() { cout << "Child::h_child()" << endl; }};class GrandChild : public Child{public: int igrandchild; GrandChild() :igrandchild(1000) {} virtual void f() { cout << "GrandChild::f()" << endl; } virtual void g_child() { cout << "GrandChild::g_child()" << endl; } virtual void h_grandchild() { cout << "GrandChild::h_grandchild()" << endl; }};/*使用了一个int** pVtab 来作为遍历对象内存布局的指针这样可以方便地像使用数组一样来遍历所有的成员包括其虚函数表了*/int main(){ typedef void(*Fun)(void); //指向函数的指针 GrandChild gc; int** pVtab = (int**)&gc; //二维 Fun pFun; cout << "[0] GrandChild::_vptr->" << endl; for (int i = 0; (Fun)pVtab[0][i] != NULL; i++){ pFun = (Fun)pVtab[0][i]; //把虚函数表对应函数赋给pFun cout << " [" << i << "] "; pFun(); } cout << "[1] Parent.iparent = " << (int)pVtab[1] << endl; cout << "[2] Child.ichild = " << (int)pVtab[2] << endl; cout << "[3] GrandChild.igrandchild = " << (int)pVtab[3] << endl; return 0;}

三个类的内存布局如下:

这里写图片描述

运行结果: 这里写图片描述


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选