C++简易接口示例

xiaoxiao2021-02-28  80

第一次做接口,虽然理论知识都懂,还是花了几天才弄出来。把实际工程精简一下记录下来。

这里共有两个工程,一个是生成含有接口的动态链接库工程,一个是使用接口的工程。

动态链接库工程:

接口类(API.h

#pragmaonce

#ifdefWIN32

#defineTEST_API__declspec(dllexport)

#else

#define TEST_API

#endif

 

classTEST_APITest

{

public:

   virtualvoid test()=0;

}; 

TEST_APITest*CreateFeaturesDetection(int type);

 

接口实现类1TestOne.h

#pragmaonce

#include"API.h"

#include<iostream>

classTestOne :

   publicTest

{

public:

   void test();

};

TestOne.cpp

#include"TestOne.h"

#include"TestTwo.h"

 

voidTestOne::test()

{

   std::cout << "this is testOne class" << std::endl;

}

Test*CreateFeaturesDetection(inttype)

{

   Test *test;

   if (type == 1)

       test = newTestOne();

   else

       test = newTestTwo();

   return test;

}

接口实现类2(TestTwo.h)

#pragmaonce

#include"API.h"

#include<iostream>

classTestTwo :

   publicTest

{

public:

   void test();

};

(TestTwo.cpp)

#include"TestTwo.h"

 

voidTestTwo::test()

{

   std::cout << "this is testTwo class" << std::endl;

}

 

 

测试工程如下:

#include"stdafx.h"

#include"\Documents\VisualStudio 2013\Projects\testdll\testdll\API.h" 

int_tmain(intargc,_TCHAR*argv[])

{

   Test* test = CreateFeaturesDetection(1);

   test->test();

   test = CreateFeaturesDetection(2);

   test->test();

   return 0;

}

运行结果如下:

转载请注明原文地址: https://www.6miu.com/read-39083.html

最新回复(0)