纯虚函数库调用 方式

本文介绍了如何使用纯虚函数创建DLL库,展示了如何在DLL中定义接口,以及在客户端如何动态创建和管理这些对象。通过实例演示了创建类继承纯虚基类并实现相应函数,以及在Win32控制台应用中调用这些功能的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天看到调用的库定位到的头文件都是纯虚函数,觉得挺有意思,也挺实用的,就写了个小Demo记录下

1、建立新dll工程(Demo是用Win32控制台应用程序)

2、新建纯虚函数头文件(VirtualBase.h)

#pragma once

#define DLL_EXPORTS
#ifdef DLL_EXPORTS
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif
class DLL_API CVirtualBase
{
public:
	virtual bool Init() = 0;
	virtual bool Uninit() = 0;
	virtual void setNum(int a, int b) = 0;
	virtual int Operate() = 0;

};

extern "C" DLL_API CVirtualBase *CreateObj();    //创建对象
extern "C" DLL_API void DestroyObj(CVirtualBase* Obj);  //销毁对象

3、创建一个类继承上面的CVirtualBase并实现响应的函数(Class1)

类.h:

#pragma once
#include "VirtualBase.h"
class CClass1 :	public CVirtualBase
{
public:
	CClass1();
	~CClass1();

	bool Init();
	bool Uninit();
	void setNum(int a, int b);
	int Operate();

private:
	int m_nA;
	int m_nB;
};

.cpp:

#include "stdafx.h"
#include "Class1.h"


CClass1::CClass1()
{
	m_nA = 1;
	m_nB = 2;
}


CClass1::~CClass1()
{
}

bool CClass1::Init()
{
	return true;
}

bool CClass1::Uninit()
{
	return true;
}

void CClass1::setNum(int a, int b)
{
	m_nA = a;
	m_nB = b;
}

int CClass1::Operate()
{
	return m_nA + m_nB;
}

DLL_API CVirtualBase *CreateObj()
{
	return new CClass1();
}

DLL_API void DestroyObj(CVirtualBase* Obj)
{
	delete Obj;
}

工程很简单,只是简单做测试,编译通过后生成vitual_dll.dll,vitual_dll.lib就可以调用了。

4、创建调用工程UseVirtualdll(Win32控制台),将VirtualBase.h,vitual_dll.lib打包放在工程目录下,像调用其他库一样配置即可,下面是调用的程序及结果

#include "stdafx.h"
#include <iostream>
#include <VirtualBase.h>

int main()
{
	CVirtualBase *pBase;
	pBase = CreateObj();  //创建
	if (pBase->Init())
		std::cout << "use dll, init success!" << std::endl;

	std::cout << pBase->Operate() << std::endl;
	pBase->setNum(3, 6);
	std::cout << pBase->Operate() << std::endl;

	if (pBase->Uninit())
		std::cout << "use dll, uninit success!" << std::endl;
	system("pause");
    return 0;
}

另:当多个类同时继承CVirtualBase时,用起来也比较方便,将CreateObj()改为CreateObj(int type),及加入类型即可,如下段代码

DLL_API CVirtualBase *CreateObj(int type)
{
	CVirtualBase *pBase;
	switch (type)
	{
	case 0:
		pBase =  new CClass1();
		break;
	case 1:
		pBase = new CClass2();
		break;
	default:
		pBase = new CClass1();
		break;
	}
	return pBase;
}

代码都贴出来了,工程就像上面一样简单,就不上传了,自己动手便知。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值