纯虚函数实现接口类:接口编程实战演练

公共的接口要求

//SocketProtocol.h
#pragma once

class SocketIF
{
public:
	//客户端初始化 获取handle 上下文信息
	virtual int cltSocketInit() = 0;

	//客户端发报文
	virtual int cltSocketSend(unsigned char *buf, int buflen) = 0;

	//客户端收报文
	virtual int cltSocketRev(unsigned char *buf, int *buflen) = 0;

	//客户端释放资源
	virtual int cltSocketDestory() = 0;
};
厂商1要求的接口原型

//SocketImp1.h
#pragma once
#include "socketprotocol.h"

class SocketImp1 :public SocketIF
{
public:
	SocketImp1(void);
	~SocketImp1(void);

public:
	int cltSocketInit();

	//客户端发报文
	int cltSocketSend(unsigned char *buf, int buflen);

	//客户端收报文
	int cltSocketRev(unsigned char *buf, int *buflen);

	//客户端释放资源
	int cltSocketDestory();
private:
	char *pcommon;
	int len;
};

接口实现

//SocketImp1.cpp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "SocketImp1.h"


SocketImp1::SocketImp1(void)
{
}


SocketImp1::~SocketImp1(void)
{
}

int SocketImp1::cltSocketInit()
{
	return 0;
}

//客户端发报文
int SocketImp1::cltSocketSend(unsigned char *buf, int buflen)
{
	pcommon = (char *)malloc((buflen + 1)*sizeof(char));
	//pcommon[len-1] = 0;
	len = buflen;
	memcpy(pcommon, buf, buflen);
	return 0;
}

//客户端收报文
int SocketImp1::cltSocketRev(unsigned char *buf, int *buflen)
{
	memcpy(buf, pcommon, len);
	*buflen = len;
	return 0;
}

//客户端释放资源
int SocketImp1::cltSocketDestory()
{
	if (pcommon != NULL)
	{
		delete[] pcommon;
	}
	return 0;
}

测试文件

//mainclass.cpp
#define _CRT_SECURE_NO_WARNINGS
#include "iostream"
#include "SocketImp1.h"
#include "SocketProtocol.h"
using namespace std;


//主框架
void mainOP01()
{
	SocketIF *sIf = new SocketImp1();

	unsigned char buf[1024];
	strcpy((char *)buf, "ddddddddddddddsssssssssssssssssssss");
	int buflen = 10;

	unsigned char out[1024];
	int outlen = 10;
	sIf->cltSocketInit();
	sIf->cltSocketSend(buf, buflen);
	sIf->cltSocketRev(out, &outlen);
	sIf->cltSocketDestory();

}

int mainOP02(SocketIF *sIf, unsigned char *in, int inlen, unsigned char *out, int *outlen)
{
	int ret = 0;
	ret = sIf->cltSocketInit();
	ret = sIf->cltSocketSend(in, inlen);
	ret = sIf->cltSocketRev(out, outlen);
	ret = sIf->cltSocketDestory();
	return ret;

}

void main()
{
	SocketIF *sIf = new SocketImp1();

	unsigned char buf[1024] = { 0 };
	strcpy((char *)buf, "ddddddddddddddsssssssssssssssssssss");
	int buflen = 10;

	unsigned char out[1024] = { 0 };
	int outlen = 10;

	mainOP02(sIf, buf, buflen, out, &outlen);

	printf("out:%s\n", out);
	delete sIf;
	system("pause");
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值