Posts Tagged ‘InterFace’

C++ struct虚拟类(接口)使用范例

星期二, 六月 18th, 2013 24 views

首先是接口的编写
InterfaceTest.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#pragma once
/************************************************************************/
/* 接口定义                                                             */
/************************************************************************/
struct ITestInterface
{
    virtual ~ITestInterface(){}
    virtual void Release() = 0;//释放接口
    virtual void TestFun() = 0;//接口函数示例

};
extern"C"
{
    ITestInterface* CreateInterface();//创建接口
};

接下来新建一个类实现这个接口:
CTest.h

1
2
3
4
5
6
7
8
9
10
11
#pragma once
#include "InterfaceTest.h"
/************************************************************************/
/* 接口实现                                                             */
/************************************************************************/
class CTest : public ITestInterface
{
public:
    virtual void Release();
    virtual void TestFun();
};

CTest.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include "CTest.h"

ITestInterface* CreateInterface()
{
    return new CTest;
}
void CTest::Release()
{
    delete this;
}

void CTest::TestFun()
{
    //这里实现接口功能
}

接下来是该接口类的使用方法

Main.cpp

1
2
3
4
5
6
7
8
#include "InterfaceTest.h"

void main()
{
    ITestInterface* test= CreateInterface();//创建接口
    test->TestFun();//执行接口函数
    test->Release();//释放接口
}

代码即讲解,最后感谢一下FG提供的方案。
本文到此,谢谢关注。

BeiTown
2013.06.18