c++ - 如何在多个类中重用一个接口(interface)实现?

标签 c++ interface abstract-class reusability

这个问题也可以命名为“如何在没有 ATL 的情况下进行引用计数”。有人问过一些类似的问题herehere ,但在前者中回答了不同的问题,并且在这两种情况下都涉及 ATL。我的问题对 C++ 更笼统,而不是关于 COM。

假设我们有一个IUnknown“接口(interface)”,像这样:

class IUnknown
{
public:
    virtual ULONG AddRef() = 0;
    virtual ULONG Release() = 0;
    virtual ULONG QueryInterface(void * iid, void **ppv) = 0;
};

...让我们加入一些其他接口(interface),它们是虚构 SDK 的一部分:

class IAnimal : public IUnknown
{
public:
    virtual IAnimal** GetParents() = 0;
};

class IMammal : public IAnimal
{
public:
    virtual ULONG Reproduce() = 0;
};

因为我要实现几种动物和哺乳动物,所以我不想在每个类中复制粘贴 AddRef()Release() 实现,所以我写了UnknownBase:

class UnknownBase : public IUnknown
{
public:
    UnknownBase()
    {
        _referenceCount = 0;
    }
    ULONG AddRef()
    {
        return ++_referenceCount;
    }
    ULONG Release()
    {
        ULONG result = --_referenceCount;
        if (result == 0)
        {
            delete this;
        }
        return result;
    }
private:
    ULONG _referenceCount;
};

...这样我就可以用它来实现一个 Cat:

class Cat : public IMammal, UnknownBase
{
public:
    ULONG QueryInterface(void *, void**);

    IAnimal** GetParents();
    ULONG Reproduce();
};

ULONG Cat::QueryInterface(void * iid, void **ppv)
{
    // TODO: implement
    return E_NOTIMPL;
}

IAnimal** Cat::GetParents()
{
    // TODO: implement
    return NULL;
}

ULONG Cat::Reproduce()
{
    // TODO: implement
    return 0;
}

...然而,编译器不同意:

c:\path\to\farm.cpp(42): error C2259: 'Cat' : cannot instantiate abstract class
          due to following members:
          'ULONG IUnknown::AddRef(void)' : is abstract
          c:\path\to\iunknown.h(8) : see declaration of 'IUnknown::AddRef'
          'ULONG IUnknown::Release(void)' : is abstract
          c:\path\to\iunknown.h(9) : see declaration of 'IUnknown::Release'

我错过了什么?

最佳答案

这不需要更改接口(interface)定义:

template<class I>
class UnknownBase : public I
{
    ...
}

class Cat : public UnknownBase<IMammal>
{
    ...
}

关于c++ - 如何在多个类中重用一个接口(interface)实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17310733/

相关文章:

c++ - CUDA 矩阵类的 operator() 重载

javascript - 难以理解 API 和 DOM

c++ - 将抽象类(仅限纯虚函数)的继承/派生限制在某个类

c++ - 如何使用 std::make_unique 函数和接口(interface)类?

java - 为什么 Java 允许从接口(interface)多重继承但不允许从抽象/具体类继承

C++内联函数指针和模板函数设计

c++ - 错误:使用已删除的函数 boost::filesystem3::directory_iterator

c++ - QMdiSubWindow 关闭后如何删除 QWidget

go - 外部包如何隐式实现接口(interface)?

c++ - 由于混合 CRTP 和接口(interface)而崩溃?