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
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择