#include <objbase.h>
interface ICalcu : IUnknown
{
virtual int __stdcall Sum(int x, int y) = 0;
virtual int __stdcall Sub(int x, int y) = 0;
virtual int __stdcall Mul(int x, int y) = 0;
virtual double __stdcall Div(int x, int y) = 0;
};
interface IRadius : IUnknown
{
virtual double __stdcall Radius(int x, int y) = 0;
};
HRESULT __stdcall CFactory::CreateInstance(IUnknown* pUnknownOuter,
const IID& iid,
void** ppv)
{
if(pUnknownOuter != NULL)
{
return CLASS_E_NOAGGREGATION;
}
CSimpleCalc2* pSc = new CSimpleCalc2;
// CSimpleCalc* pSc = new CSimpleCalc;
if(pSc == NULL)
{
return E_OUTOFMEMORY;
}
HRESULT hr = pSc->InitContainment() ;
if (FAILED(hr))
{
// Initialization failed. Delete component.
pSc->Release() ;
return hr ;
}
/* HRESULT */hr = pSc->QueryInterface(iid,ppv);
pSc->Release();
return hr;
}
#include "interface.h"
class CSimpleCalc2 : public IRadius
{
public:
...
// ICalcu
virtual double __stdcall Radius(int x, int y);
...
HRESULT InitContainment() ;
private:
...
ICalcu *m_pCal ;
};
#include <math.h>
...
CSimpleCalc2::~CSimpleCalc2()
{
InterlockedDecrement(&g_cComponents);
if (m_pCal != NULL)
{
m_pCal->Release() ;
}
}
HRESULT CSimpleCalc2::InitContainment()
{
HRESULT hr = ::CoCreateInstance(CLSID_COMPONENT,
NULL,
CLSCTX_INPROC_SERVER,
IID_ICalcu,
(void**)&m_pCal) ;
if (FAILED(hr))
{
return E_FAIL ;
}
else
{
return S_OK ;
}
}
double __stdcall CSimpleCalc2::Radius(int x, int y)
{
int x2, y2, z2;
x2 = m_pCal->Mul(x,x);
y2 = m_pCal->Mul(y,y);
z2 = m_pCal->Sum(x2,y2);
return sqrt(z2);
}