温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

接口的实现以及QueryInterface的实现和使用方法

发布时间:2021-10-14 09:58:29 来源:亿速云 阅读:153 作者:柒染 栏目:编程语言

这篇文章给大家介绍接口的实现以及QueryInterface的实现和使用方法,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

interface IX : public IUnknown
{
virtual void _stdcall Fx() = 0;
};

interface IY : public IUnknown
{
virtual void _stdcall Fy() = 0;
};

interface IZ : public IUnknown
{
virtual void _stdcall Fz() = 0;
};

static const IID IID_IX = {0xff5ba880, 0xa371, 0x4a42, {0x87, 0x20, 0x96, 0xe0, 0x4d, 0x68, 0xd, 0x76}}; // {FF5BA880-A371-4a42-8720-96E04D680D76}
static const IID IID_IY = {0xde44d538, 0xe926, 0x4d5f, {0x94, 0x5d, 0x61, 0x83, 0x86, 0x7c, 0x63, 0x41}}; // {DE44D538-E926-4d5f-945D-6183867C6341}
static const IID IID_IZ = {0x91157d15, 0x22b1, 0x45d9, {0xb4, 0xc9, 0x81, 0x3, 0x8d, 0xec, 0xef, 0xad}};   // {91157D15-22B1-45d9-B4C9-81038DECEFAD}

class CA : public IX,
public IY
{
public:
virtual HRESULT _stdcall QueryInterface(REFIID riid, __RPC__deref_out void **ppvObject);
virtual ULONG _stdcall AddRef() { return 0; }
virtual ULONG _stdcall Release() { return 0; }

virtual void _stdcall Fx() { cout<<"IX::Fx"<<endl; }

virtual void _stdcall Fy() { cout<<"IY::Fy"<<endl; }
};

HRESULT _stdcall CA::QueryInterface(REFIID riid, __RPC__deref_out void **ppvObject)
{
if(IID_IX == riid)
{
*ppvObject = static_cast<IX*>(this);
}
else if(IID_IY == riid)
{
*ppvObject = static_cast<IY*>(this);
}
else if(IID_IUnknown == riid)
{
//*ppvObject = static_cast<IUnknown*>(this); //这样为什么不行
*ppvObject = static_cast<IX*>(this);
}
else
{
*ppvObject = NULL;
return E_NOINTERFACE;
}

reinterpret_cast<IUnknown*>(*ppvObject)->AddRef();
return S_OK;
}

IUnknown* CreateInstance()
{
IUnknown *pIUnk = static_cast<IX*>(new CA);
pIUnk->AddRef();
return pIUnk;
}

void _tmain(int argc,_TCHAR*argv[])
{
IUnknown *pIUnk = CreateInstance();

IX *pIX = NULL;
HRESULT hr = pIUnk->QueryInterface(IID_IX,(void**)&pIX);
if(SUCCEEDED(hr))
{
pIX->Fx();
}

IY *pIY = NULL;
hr = pIUnk->QueryInterface(IID_IY,(void**)&pIY);
if(SUCCEEDED(hr))
{
pIY->Fy();
}

IZ *pIZ = NULL;
hr = pIUnk->QueryInterface(IID_IZ,(void**)&pIZ);
if(SUCCEEDED(hr))
{
cout<<"Succeed to find pIZ"<<endl;
pIZ->Fz();
}

IY *pIYFromIX = NULL;
hr = pIX->QueryInterface(IID_IY,(void**)&pIYFromIX);
if(SUCCEEDED(hr))
{
pIYFromIX->Fy();
}

IUnknown *pIUnkFromIY = NULL;
hr = pIY->QueryInterface(IID_IUnknown,(void**)&pIUnkFromIY);
if(SUCCEEDED(hr))
{
if(pIUnkFromIY == pIUnk)
cout<<"pIUnkFromIY == pIUnk"<<endl;
else
  cout<<"pIUnkFromIY != pIUnk"<<endl;
}

if(pIUnk) delete pIUnk;
}

关于接口的实现以及QueryInterface的实现和使用方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI