內容概要:
滿足下面2個條件時,
1. 父類有虛函數,子類無虛函數(即無虛函數重寫或無虛函數覆蓋)
2. 非虛繼承
類對象之記憶體布局
前述相關內容參考:
1. http://blog.csdn.net/pathuang68/archive/2009/04/20/4096088.aspx
2. http://blog.csdn.net/pathuang68/archive/2009/04/21/4096429.aspx
3. http://blog.csdn.net/pathuang68/archive/2009/04/21/4096521.aspx
Base類中有兩個虛函數vfBase_1()、vfBase_2()和一個整形成員變數m_base, Derived類中有一個整形成員變數m_derived,二者的關係如下:
代碼如下:
#include <iostream>
using namespace std;
class Base
{
public:
int m_base;
inline virtual void vfBase_1()
{
cout << "This is in Base::vfBase_1()" << endl;
}
inline virtual void vfBase_2()
{
cout << "This is in Base::vfBase_2()" << endl;
}
};
class Derived : public Base
{
public:
int m_derived;
};
typedef void (*VFun)(void);
// 改為template形式,因為不能確定傳進來的參數是Base類型的指標還是Derived類型的指標
template<typename T>
VFun virtualFunctionPointer(T* b, int i)
{
return (VFun)(*((int*)(*(int*)b) + i));
}
int main(void)
{
Derived d;
cout << "The size of Base object = /t" << sizeof(Derived) << endl;
cout << endl;
int i = 0;
while(virtualFunctionPointer(&d, i))
{
VFun pVF = virtualFunctionPointer(&d, i++);
pVF();
}
return 0;
}
運行結果如下:
Derived對象的memory layout圖解如下:
後篇:http://blog.csdn.net/pathuang68/archive/2009/04/23/4101977.aspx