第一种方式就是子类重写父类的方法,在子类中定义和父类同样的方法,方法体中调用父类的方法
父类代码
#pragma once
#include "CClientSocket.h"
class CTCPInterface
{
public:
CTCPInterface();
~CTCPInterface();
public:
CClientSocket m_Socket;
bool m_bConnected;
int m_nTimeout;
CString m_strFeedback;
int m_nValue;
public:
bool Connect(CString ip, int port);
bool SendCmd(CString cmd);
};
#include "CTCPInterface.h"
#include <exception>
#include <string>
#include "../Utils/CCommon.h"
CTCPInterface::CTCPInterface()
{
m_bConnected = false;
m_nTimeout = 200;
m_nValue = -1;
}
CTCPInterface::~CTCPInterface()
{
}
bool CTCPInterface::Connect(CString ip, int port)
{
bool b_Result = false;
try
{
b_Result = m_Socket.Connect(ip, port);
}
catch (const std::exception&)
{
}
return b_Result;
}
bool CTCPInterface::SendCmd(CString cmd)
{
bool b_Result = false;
try
{
memset(m_Socket.BufferData, 0, sizeof(m_Socket.BufferData));
string tmp = cmd.GetBuffer(0);
CCommon::ReplaceAll(tmp, " ", "");
int len = tmp.length() / 2;
BYTE* bytes = new BYTE[len];
CCommon::HexStrToBytes(tmp, len, bytes);
m_Socket.Send(bytes, len);
Sleep(m_nTimeout);
b_Result = true;
CString str;
str = CCommon::BytesToCString(bytes, len);
OutputDebugString(str);
}
catch (const std::exception&)
{
}
return b_Result;
}
子类代码
#pragma once
#include "CClientSocket.h"
#include "CTCPInterface.h"
class __declspec(dllexport) CPLCService:public CTCPInterface
{
public:
CPLCService();
~CPLCService();
public:
bool Connect(CString ip, int port);
bool SendCmd(CString cmd);
};
#include "CPLCService.h"
#include <exception>
#include <string>
#include "../Utils/CCommon.h"
CPLCService::CPLCService()
{
}
CPLCService::~CPLCService()
{
m_Socket.Close();
}
bool CPLCService::Connect(CString ip, int port)
{
return CTCPInterface::Connect(ip, port);
}
bool CPLCService::SendCmd(CString cmd)
{
return CTCPInterface::SendCmd(cmd);
}
第二种方法
在使用的地方定义基类的指针,指向new的子类,需要用子类时候,再将父类指针强转为子类的指针