//采用多重继承方式,模拟实现COM接口和COM对象的例子
#define IID_IUnknown 1
#define IID_IVideo 2
#define IID_IAudio 3
struct IUnknown
{
virtual BOOL QueryInterface(int nIid, void **ppvObj)=0;
virtual DWORD Release()=0;
virtual DWORD AddRef()=0;
};
class IVideo:virtual public IUnknown //接口类定义
{
public:
virtual BOOL OpenVideoChannel()=0;
virtual BOOL CloseVideoChannel()=0;
virtual DWORD GetVideoChannelState()=0;
};
class IAudio:virtual public IUnknown //接口类定义
{
virtual BOOL OpenAudioChannel()=0;
virtual BOOL CloseAudioChannel()=0;
virtual void TransferAudio()=0;
virtual DWORD GetAudioChannelState()=0;
};
class CVisiblePhone:public IAudio,public IVideo //COM对象类定义
{
public:
CVisiblePhone();
~CVisiblePhone();
public:
//IUnknown memeber function
HRESULT QueryInterface(int nIid, void **ppvObj);
DWORD Release();
DWORD AddRef();
//IVudio memeber function
BOOL OpenVideoChannel();
BOOL CloseVideoChannel();
DWORD GetVideoChannelState();
//IAideo memeber function
BOOL OpenAudioChannel();
BOOL CloseAudioChannel();
void TransferAudio();
DWORD GetAudioChannelState();
private:
DWORD m_Ref;
};
//实现接口查询函数QueryInterface()
HRESULT CVisiblePhone::QueryInterface(int iid,void **ppvObj)
{
if (iid==IID_IUnknown)
{
*ppvObj=(IUnknown *)((IVideo *)this);
((IUnknown *)*ppvObj)->AddRef();
}
else if (iid==IID_IVideo)
{
*ppvObj=(IVideo *)this;
((IVideo *)*ppvObj)->AddRef();
}
else if (iid==IID_IAudio)
{
*ppvObj=(IAudio *)this;
((IAudio *)*ppvObj)->AddRef();
}
else
{
*ppvObj=NULL;
return E_NOINTERFACE;
}
return S_OK;
}
//采用内嵌类的方式在一个COM对象中实现多个接口
#define IID_IUnknown 1
#define IID_IVideo 2
#define IID_IAudio 3
class CVisiblePhone//COM对象类定义
{
public:
CVisiblePhone();
~CVisiblePhone();
public:
//IUnknown memeber function
HRESULT QueryInterface(int nIid, void **ppvObj);
DWORD Release();
DWORD AddRef();
//embeded IAudio
class CAudioObj:public IAudio
{
//IUnknown memeber function
HRESULT QueryInterface(int nIid, void **ppvObj);
DWORD Release();
DWORD AddRef();
//IAideo memeber function
BOOL OpenAudioChannel();
BOOL CloseAudioChannel();
void TransferAudio();
DWORD GetAudioChannelState();
}m_AudioObj;
//embeded IVudio
class CVideoObj:public IVideo
{
//IUnknown memeber function
HRESULT QueryInterface(int nIid, void **ppvObj);
DWORD Release();
DWORD AddRef();
//IVudio memeber function
BOOL OpenVideoChannel();
BOOL CloseVideoChannel();
DWORD GetVideoChannelState();
}m_VideoObj;
private:
DWORD m_Ref;
};
//实现接口查询函数QueryInterface()
HRESULT CVisiblePhone::QueryInterface(int iid,void **ppvObj)
{
if (iid==IID_IUnknown)
{
*ppvObj=(IUnknown *)&m_VideoObj;
AddRef();
}
else if (iid==IID_IVideo)
{
*ppvObj=&m_VideoObj;
AddRef();
}
else if (iid==IID_IAudio)
{
*ppvObj=&m_AudioObj;
AddRef();
}
else
{
*ppvObj=NULL;
return E_NOINTERFACE;
}
return S_OK;
}