The abstract class of C ++ can be used as an interface to implement Event Callback and other mechanisms.
Interface implementation file idemoimpl. cpp
#include <stdio.h>#include "IDemo.h"IDemo::IDemo(){}IDemo::~IDemo(){}class CDemoImpl : public IDemo{public:CDemoImpl(){};~CDemoImpl(){};public:virtual int Add(int a, int b){return (a+b);}virtual int Sub(int a, int b){return (a-b);}};IDemo * GetInstance(void){return new CDemoImpl();}
Interface file idemo. h
#ifndef _IDEMO_H_#define _IDEMO_H_class IDemo{public:IDemo();virtual ~IDemo();public:virtual int Add(int, int) = 0;virtual int Sub(int, int) = 0;};IDemo * GetInstance(void);#endif
The client of the object can call
#include "IDemo.h"int main(void){ IDemo * pDemo = GetInstance(); printf("%d\n", pDemo->Add(1,2));}
If idemoimpl. cpp is compiled into DLL or so, and then only the implementation of the interface file idemo. h and binary is published, a little of the prototype of COM is available.
This getinstance () is still too simple. If you can change it to another ID to specify different objects,
For example, getinstance (const char * UUID), then this function has the meaning of QueryInterface () of some MS iunkown interfaces.
HRESULT QueryInterface( [in] REFIID riid, [out] void **ppvObject);
Refer to QueryInterface to implement a getinstance ()
void * GetInstance(const char * uuid){ if (!strcmp(uuid, "uuid_add") return new CDemoAddImpl(); if (!strcmp(uuid, "uuid_sub") return new CDemoSubImpl(); return (void *) 0;}
Modify a new idemo. h
#ifndef _IDEMO_H_#define _IDEMO_H_#ifdef __cplusplusextern "C"{#endifvoid * GetInstance(const char * uuid);#ifdef __cplusplus};#endif#endif
Separate interface definitions of different functions
Idemoadd. h
#ifndef _IDEMO_ADD_H_#define _IDEMO_ADD_H_class IDemoAdd{public:IDemoAdd();virtual ~IDemoAdd();public:virtual int Add(int, int) = 0;}#endif
Idemosub. h
#ifndef _IDEMO_SUB_H_#define _IDEMO_SUB_H_class IDemoSub{public:IDemoSub();virtual ~IDemoSub();public:virtual int Sub(int, int) = 0;}#endif
Use the cdemoaddimpl class and cdemosubimpl class in two CPP files to implement the add () and sub () methods (omitted)
Then, compile the implemented CPP into a binary DLL or so file, and release it together with the three header files (idemo. h idemoadd. h idemosub. h) to the client.
The client call can be as follows:
#include <stdio.h>#include "IDemo.h"#include "IDemoAdd.h"#include "IDemoSub.h"int main(void){ IDemoAdd * pAdd = GetInstance("uuid_add"); if (pAdd) pAdd->Add(1,2); IDemoSub * pSub = GetInstance("uuid_sub"); pSub->Sub(1,2); return 0;}
Summary:
The basic idea of COM is to expose the object interface (header file), but hide the implementation details of the object interface (Binary library ). Through the definition of these interfaces, the client can create new software at the binary level like building blocks, so as to achieve software reuse.