我有一个共享基类CMyBase,它进一步分为子类CMyFirst和CMySecond。如何为客户端实现工厂接口,以便他们不需要知道使用CComObjects创建了哪些子项?
基本上我要做的是:
CMyBase* CFactory::Create
{
CMyBase* pInst = NULL;
if (something)
{
pInst = new CMyFirst();
}
else
{
pInst = new CMySecond();
}
return pInst;
}
但是如何创建子COM对象的实例呢?
CComObject<CMyBase>* CFactory::Create
{
HRESULT hr = E_FAIL;
CComObject<CMyBase>* pInst = NULL;
if (something)
{
hr = CComObject<CMyFirst>::CreateInstance(&pInst); // compiler error (see below)
}
else
{
hr = CComObject<CMySecond>::CreateInstance(&pInst); // compiler error (see below)
}
if (SUCCEEDED(hr))
{
pInst->AddRef();
}
return pInst;
}
我明白为什么会收到此错误,但我怎么能这样做呢?
error C2664: 'ATL::CComObject<Base>::CreateInstance' : cannot convert parameter 1 from 'ATL::CComObject<Base> *' to 'ATL::CComObject<Base> **'
答案 0 :(得分:2)
首先创建派生类,然后在返回之前将其强制转换为基础。
一个例子:
CComObject<CMyBase>* CFactory::Create
{
HRESULT hr = E_FAIL;
CComObject<CMyBase>* pInst = NULL;
if (something)
{
CComObject<CMyFirst>* pFirst = NULL;
hr = CComObject<CMyFirst>::CreateInstance(&pFirst);
pInst = (CComObject<CMyBase>*)pFirst;
}
else
{
CComObject<CMySecond>* pSecond = NULL;
hr = CComObject<CMySecond>::CreateInstance(&pSecond);
pInst = (CComObject<CMyBase>*)pSecond;
}
if (SUCCEEDED(hr))
{
pInst->AddRef();
}
return pInst;
}