对象内存布局 (5)
来源:互联网 发布:cms什么意思 编辑:程序博客网 时间:2024/06/05 18:56
内容概要:
满足下面3个条件时,
1. 父类有虚函数,子类也有虚函数,且子类的虚函数重写或覆盖了父类的虚函数
2. 非虚继承
3. 多重继承
类对象之内存布局
前篇: http://blog.csdn.net/pathuang68/archive/2009/04/23/4101981.aspx
多重继承,派生类不重写基类中的虚函数。
假定各类之间的关系如下图:
代码如下:
#include <iostream>
using namespace std;
class Base1
{
public:
int m_base1;
inline virtual void vfBase1_1()
{
cout << "This is in Base1::vfBase1_1()" << endl;
}
inline virtual void vfBase1_2()
{
cout << "This is in Base1::vfBase1_2()" << endl;
}
};
class Base2
{
public:
int m_base2;
inline virtual void vfBase2_1()
{
cout << "This is in Base2::vfBase2_1()" << endl;
}
inline virtual void vfBase2_2()
{
cout << "This is in Base2::vfBase2_2()" << endl;
}
};
class Base3
{
public:
int m_Base3;
inline virtual void vfBase3_1()
{
cout << "This is in Base3::vfBase3_1()" << endl;
}
inline virtual void vfBase3_2()
{
cout << "This is in Base3::vfBase3_2()" << endl;
}
};
class Derived : public Base1, public Base2, public Base3
{
public:
int m_derived;
inline virtual void fd()
{
cout << "This is in Derived::fd()" << endl;
}
};
typedef void (*VFun)(void);
template<typename T>
VFun virtualFunctionPointer(T* b, int i)
{
return (VFun)(*((int*)(*(int*)b) + i));
}
int main(void)
{
Derived d;
cout << "The size of Derived object = /t" << sizeof(Derived) << endl;
cout << endl;
cout << "1st virtual function table: " << endl;
int i = 0;
while(virtualFunctionPointer(&d, i))
{
VFun pVF = virtualFunctionPointer(&d, i++);
pVF();
}
cout << endl;
cout << "2nd virtual function table: " << endl;
i = 0;
int* tmp = ((int*)&d) + 2;
while(virtualFunctionPointer(tmp, i))
{
VFun pVF = virtualFunctionPointer(tmp, i++);
pVF();
}
cout << endl;
cout << "3rd virtual function table: " << endl;
i = 0;
tmp = ((int*)&d) + 4;
while(virtualFunctionPointer(tmp, i))
{
VFun pVF = virtualFunctionPointer(tmp, i++);
pVF();
}
return 0;
}
运行结果如下:
Derived对象之memory layout如下:
由上面的分析可知:
其一:有三个虚函数表
其二:在Derived类中定义的虚函数Derived::vfDerived()附加在一个虚函数表的最后
- 对象内存布局 (5)
- 对象内存布局 (5)
- 对象内存布局 (5)
- C++内存对象布局
- c++对象,内存布局
- c++对象内存布局
- 对象内存布局 (1)
- 对象内存布局 (2)
- 对象内存布局 (3)
- 对象内存布局 (4)
- 对象内存布局 (6)
- 对象内存布局 (7)
- 对象内存布局 (8)
- 对象内存布局 (9)
- 对象内存布局 (10)
- 对象内存布局 (11)
- 对象内存布局 (12)
- 对象内存布局 (13)
- 成长,没你想象的那么迫切!
- Broadcast Receiver(三)广播接收器的优先级
- 认识系统服务
- 对象内存布局 (4)
- C++ 单例模式
- 对象内存布局 (5)
- Const,Const函数,Const变量,函数后面的Const
- 设计模式 之 工厂模式
- 基于 Android NDK 的学习之旅-----数据传输(基本数据类型和数组传输)
- 反转链表非递归/递归d
- 从给定字符串中寻找子串,如果存在子串,返回子串初始位置
- 对动态数组用 选择排序算法排序(C语言)
- vmware下安装ubuntu键盘不能使用 root默认密码
- 对象内存布局 (6)