//Component1是一个实现了两个接口IX和IY的外部组件,但它复用了组件2---组件1所包容的一个内部组件---对IY的实现。
class CA : public IX,public IY{
public:
virtual HRESULT __stdcall QueryInterface(const IID& iid,void** ppv);
virtual ULONG __stdcall AddRef();
virtual ULONG __stdcall Release();
virtual void __stdcall Fx(){cout<<"Fx"<<endl;}
virtual void __stdcall Fy(){m_pIY->Fy();}
CA();
~CA();
HRESULT Init();
private:
long m_cRef;
IY* m_pIY;
};
CA::CA():m_cRef(1),m_pIY(NULL){
InterlockedIncrement(&g_cComponents);
}
CA::~CA(){
InterlockedDecrement(&g_cComponents);
trace("Destroy self.");
if(m_pIY != NULL) m_pIY->Release();
}
HRESULT CA::Init(){
trace("Create Contained component.");
HRESULT hr = ::CoCreateInstance(CLSID_Component2,NULL,CLSCTX_INPROC_SERVER,IID_IY,(void**)&m_pIY);
if(Failed(hr)){
trace("Could not create contained component.");
return E_FAIL;
}
else{
return S_OK;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
HRESULT __stdcall CFactory::CreateInstance(IUnknown* pUnknown,const IID& iid,void** ppv){
if(pUnknown != NULL) return CLASS_E_NOAGGREGATION;
CA* pA = new CA;
if(pA == NULL) return E_OUTOFMEMORY;
HRESULT hr = pA->Init();
if(Failed(hr)){
pA->Release();
return hr;
}
hr = pA->QueryInterface(iid,ppv);
pA->Release();
return hr ;
}
原文链接:https://www.f2er.com/javaschema/285362.html