1

我有几个接口,例如 IA、IB、IC 等,它们共享共同的属性,例如 Site。我想知道如何为这些接口重用代码(请保存我关于 COM 聚合的答案)。

目前的实现如下:

class CA
// ATL specific...
{
    STDMETHODIMP get_Site(...) {...}
    STDMETHODIMP put_Site(...) {...}
}

class BA
// ATL specific...
{
    STDMETHODIMP get_Site(...) {...}
    STDMETHODIMP put_Site(...) {...}
}

class CC
// ATL specific...
{
    STDMETHODIMP get_Site(...) {...}
    STDMETHODIMP put_Site(...) {...}
}

我想要实现(但不能)如下。

template<typename T>
class SharedProperties
{
    STDMETHODIMP get_Site(...) {...}
    STDMETHODIMP put_Site(...) {...}
}

class CA :
// ATL specific...
SharedProperties<CA>
{
    // properties are inherited and are accessible from IC
}

class BA
// ATL specific...
SharedProperties<CB>
{
    // properties are inherited and are accessible from IB
}

class CC
// ATL specific...
SharedProperties<CC>
{
// properties are inherited and are accessible from IA
}

我在阅读( http://vcfaq.mvps.org/com/7.htm )后遇到了这个想法,但该网站没有一个工作示例,无论我尝试了多少,我都无法让它工作。我不断收到“无法实例化抽象类”,因为未实现纯虚函数 get_Site 和 put_Site(根据第二个片段)。

编辑 请注意我使用的是 VS2010。下面的示例实现:

class ATL_NO_VTABLE CArticle :
    public CComObjectRootEx<CComSingleThreadModel>,
    public CComCoClass<CArticle, &CLSID_Article>,
    public IDispatchImpl<IArticle, &IID_IArticle, &LIBID_GeodeEdiLib, /*wMajor =*/ 1, /*wMinor =*/ 0>
{
public:
    CArticle()
    {
    }
4

1 回答 1

0

The compiler does not know that the methods get_Site and put_Siteimplement the methods from the interface. You need to inherit the SharedProperties class template from the corresponding interface. That's the argument to make SharedProperties a template at all.

interface IA
{
    STDMETHOD(get_Site)() = 0;
    STDMETHOD(put_Site)() = 0;
};

template<typename T>
class Sharedproperties : T
{
public:
    STDMETHODIMP get_Site() { return E_NOTIMPL; };
    STDMETHODIMP put_Site() { return E_NOTIMPL; };
};

class CAX : public IA
{
    STDMETHOD(other)() { return S_OK; }
}

class CA: public Sharedproperties<CAX>
{
public:
    CA() {}
};

Please note that the class CA is not directly inherited from the interface IA.

Edit: The VS2008 class wizard generates this inheritance for a simple ATL class object:

class ATL_NO_VTABLE CMyObject :
    public CComObjectRootEx<CComMultiThreadModel>,
    public CComCoClass<CMyObject, &CLSID_MyObject>,
    IMyObject

where IMyObject is the in the IDL defined interface. So in ATL context you just need to replace the IMyObject inheritance:

class ATL_NO_VTABLE CMyObject :
    public CComObjectRootEx<CComMultiThreadModel>,
    public CComCoClass<CMyObject, &CLSID_MyObject>,
    public Sharedproperties<MyIntermediateClass>
于 2012-05-28T08:07:50.357 回答