FateNo13 2017-02-25 12:47 采纳率: 0%
浏览 1175

在模板父类中调用子类函数的问题

下面这小段代码,可以编译执行,问题在注释里写的很清楚

#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;

}

  • 写回答

1条回答 默认 最新

  • lin_not_for_codes 2017-02-25 13:09
    关注

    父类想调用子类不是继承吧,是多态吧

    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?