模拟虚函数机制
// Base.h: interface for the Base class.//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_BASE_H__BC0F931E_FB88_46BB_AACF_81A971F3B966__INCLUDED_)
#define AFX_BASE_H__BC0F931E_FB88_46BB_AACF_81A971F3B966__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <iostream.h>
#include <memory.h>
class Base;
typedef void (Base::*FUNC_TYPE1)();
class Base
{
public:
static FUNC_TYPE1 m_VTable[];
FUNC_TYPE1 *m_lpVTable;
public:
Base();
~Base();
public:
void vsSayHello()
{
cout << "BASE::SAYHELLO" << endl;
}
void vsSayGoodBye()
{
cout << "BASE::SAYGOODBYE" << endl;
}
};
#endif // !defined(AFX_BASE_H__BC0F931E_FB88_46BB_AACF_81A971F3B966__INCLUDED_)
// Base.cpp: implementation of the Base class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Base.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
FUNC_TYPE1 Base::m_VTable[] = {
Base::vsSayHello,
Base::vsSayGoodBye
};
Base::Base()
{
m_lpVTable = Base::m_VTable;
}
Base:: ~Base()
{
}// Derive.h: interface for the Derive class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_DERIVE_H__FB413D6B_2A11_40FB_9B58_E32FEF4FA050__INCLUDED_)
#define AFX_DERIVE_H__FB413D6B_2A11_40FB_9B58_E32FEF4FA050__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "Base.h"
class Derive;
typedef void (Derive::*FUNC_TYPE2)();
class Derive : public Base
{
public:
static FUNC_TYPE2 m_VTable[];
public:
Derive();
~Derive();
public:
void vsSayHello()
{
cout << "Derive::SAYHELLO" << endl;
}
void vsSayGoodBye()
{
cout << "Derive::SAYGOODBYE" << endl;
}
};
#endif // !defined(AFX_DERIVE_H__FB413D6B_2A11_40FB_9B58_E32FEF4FA050__INCLUDED_)
// Derive.cpp: implementation of the Derive class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Derive.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
FUNC_TYPE2 Derive::m_VTable[] = {
Derive::vsSayHello,
Derive::vsSayGoodBye
};
Derive::Derive()
{
memcpy(Derive::m_VTable, m_lpVTable, 4);
m_VTable = Derive::vsSayHello;
m_VTable = Derive::vsSayGoodBye;
m_lpVTable = (FUNC_TYPE1 *)Derive::m_VTable;
}
Derive:: ~Derive()
{
}// 模拟虚函数机制.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Derive.h"
void CallFunction(Base* lpBase)
{
(lpBase->*(lpBase->m_lpVTable))();
(lpBase->*(lpBase->m_lpVTable))();
}
int main(int argc, char* argv[])
{
Base theBase;
Derive theDerive;
CallFunction(&theBase);
CallFunction(&theDerive);
return 0;
}
/:002 不会c,看不懂……
页:
[1]