今天一大早就把例子完成了
#include <objbase.h>
#include <unknwn.h>
#include <iostream>
using namespace std;
interface IX:IUnknown{
virtual void __stdcall FX() = 0;
};
interface IY:IUnknown{
virtual void __stdcall FY() = 0;
};
interface IZ:IUnknown{
virtual void __stdcall FZ() = 0;
};
extern const IID IID_IX;
extern const IID IID_IY;
extern const IID IID_IZ;
class CA:public IX,
public IY
{
virtual void __stdcall FY() {cout <<"CA::FY"<<endl; }
virtual void __stdcall FX() {cout <<"CA::FX"<<endl; }
virtual HRESULT STDMETHODCALLTYPE QueryInterface(
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject)
{
if(riid == IID_IX)
{
*ppvObject = static_cast<IX*>(this);
}
else if(riid == IID_IY)
{
*ppvObject = static_cast<IY*>(this);
}
else if(riid == IID_IUnknown)
{
*ppvObject = static_cast<IX*>(this);
}
else
{
*ppvObject = NULL;
return E_NOINTERFACE;
}
reinterpret_cast<IUnknown *>(*ppvObject)->AddRef();
return S_OK;
}
virtual ULONG STDMETHODCALLTYPE AddRef( void){ return 0; }
virtual ULONG STDMETHODCALLTYPE Release( void) {return 0; }
};
IUnknown * CreateInstance()
{
IUnknown * pI = static_cast <IX*>(new CA);
pI->AddRef();
return pI;
}
// {1A5EE493-AD77-4224-9A78-5F2DD3874714}
static const IID IID_IX =
{ 0x1a5ee493, 0xad77, 0x4224, { 0x9a, 0x78, 0x5f, 0x2d, 0xd3, 0x87, 0x47, 0x14 } };
// {AB55D03D-2160-4197-8AD2-36A36E33F69B}
static const IID IID_IY =
{ 0xab55d03d, 0x2160, 0x4197, { 0x8a, 0xd2, 0x36, 0xa3, 0x6e, 0x33, 0xf6, 0x9b } };
// {5443E124-25A6-451e-A634-2BA392788C38}
static const IID IID_IZ =
{ 0x5443e124, 0x25a6, 0x451e, { 0xa6, 0x34, 0x2b, 0xa3, 0x92, 0x78, 0x8c, 0x38 } };
int _tmain(int argc, _TCHAR* argv[])
{
HRESULT hr;
IUnknown *pUnknown = CreateInstance();
IX *pIX = NULL;
hr = pUnknown->QueryInterface(IID_IX,(void **)(&pIX));
if(SUCCEEDED(hr))
{
pIX->FX();
}
IY *pIY = NULL;
hr = pUnknown->QueryInterface(IID_IY,(void **)(&pIY));
if(SUCCEEDED(hr))
{
pIY->FY();
}
delete pUnknown;
return 0;
}
/*
口QueryInterface 返回的总是同一IUnknown指针
口若客户曾经获取过某个接口.那么它将总能获取此接口。
口客户可以再次获取已经拥有的接口。
口客户可以返回到起始接口。
口若能够从某个接口获取某特定接口,那么可以从任意接口都将可以获取此接口
下面我们将详细讨论这些规则。
*/