下面这小段代码,可以编译执行,问题在注释里写的很清楚
#include "stdafx.h"
#include
using namespace std;
struct ISystemEventListener
{
public:
virtual void OnSystemEventAnyThread() {}
};
class INetMsgEvent
{
public:
virtual void OnNetMessage(void* pMsgHeader, void* pMsgData, void* pHandler) = 0;
};
template
class CNetMsgEventHandler:public INetMsgEvent
{
public:
typedef void (TNetEventHandler::*PEventHandler)(void* pMsgHeader, void* pMsgData);
inline TNetEventHandler* This()
{
return dynamic_cast<TNetEventHandler*>(this);
}
template<typename TargetType, typename SourceType>
TargetType UnionCastType(SourceType src)
{
union
{
TargetType TargetValue;
SourceType SourceValue;
}Convert;
Convert.SourceValue = src;
return Convert.TargetValue;
}
virtual void OnNetMessage(void* pMsgHeader, void* pMsgData, void* pHandler)
{
if (pMsgHeader && pMsgData && pHandler)
{
PEventHandler pFunction = UnionCastType<PEventHandler>(pHandler);
TNetEventHandler* pSystem = This();
(pSystem->*pFunction)(pMsgHeader,pMsgData); //如果继承了ISystemEventListener,那么这一句的汇编就多出好几句,导致ecx寄存器出错
// 上面那一句,正确的时候,是下面这样的
/*__asm
{
push ecx
push edx
mov ecx,dword ptr [pMsgData]
push ecx
mov edx,dword ptr [pMsgHeader]
push edx
mov ecx,dword ptr [pSystem]
call dword ptr [pFunction]
pop edx
pop ecx
}*/
}
}
};
class A:public CNetMsgEventHandler,public ISystemEventListener //不继承ISystemEventListener的话,上面就是对的,继承了,就是错的
{
public:
int ia;
void func1(void* pMsgHeader, void* pMsgData);
};
void A::func1(void* pMsgHeader, void* pMsgData)
{
cout<<"A::func1"<<(int)pMsgHeader<<(int)pMsgData<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
A a;
a.OnNetMessage((void*)333,(void*)333,(void*)333);
return 0;
}
父类想调用子类不是继承吧,是多态吧