允许其他基class实现一个虚函数

Allow other base class to implement a virtual function

是否可以做到以下几点:
我的基础 class 有 3 个纯虚函数。我的派生 class 实现了其中的 2 个虚函数,并继承了另一个 class 实现了最后的第三个虚函数。

我当前的代码无法编译所以我认为这是无效的?如果我能以某种方式使用这种方法,那就太好了。以下是我对这种方法的实践application/use。

关于我可以用来实现此功能的不同方法的任何建议?

class ListBox
{
public:
    virtual void onScroll() = 0;
    virtual void foo() = 0;
    virtual void bar() = 0;
};

class DragScrollHandler
{
public:
    void onScroll()
    {
        ...
    }
};

class HorzListBox: public ListBox, public DragScrollHandler // could also do public HoverScrollHandler, etc.
{
public:
    void foo() override
    {
        printf("foo\n");
    }

    void bar() override
    {
        printf("foo\n");
    }

    HorzListBox()
        : ListBox(), DragScrollHandler()
    {

    }
};

Any suggestions of a different approach I could use to achieve this functionality?

将派生的 class 实现传递给另一个基础 class 实现。

class HorzListBox: public ListBox, public DragScrollHandler
{
public:
    void foo() override
    {
        printf("foo\n");
    }

    void bar() override
    {
        printf("foo\n");
    }

    void onScroll() override
    {
       DragScrollHandler::onScroll();
    }

    HorzListBox()
        : ListBox(), DragScrollHandler()
    {

    }
};

My current code won't compile so I am thinking this is not valid?

当然编译不过! Dervied class 不会覆盖抽象基础 class 的所有纯虚函数,反过来它们自己也会成为抽象 class。这意味着 Derived class 无法实例化,因此出现编译时错误。

因此,在您的情况下,Class HorzListBox 也是一个抽象 class,因为它不会覆盖 class ListBox 的所有 PVF。

请重新考虑这些行并相应地修改您的代码。

ListBoxDragScrollHandlera priori不同的概念,所以没有那种跨越多重继承的link。我的意思是在以某种方式继承的虚拟 onScroll 和另一个不相关的(另一个)分支上的 onScroll 实现之间设置 link 不是自动的。

您可以在HorzListBox上定义它来调用继承的实现:

void onScroll() override {
   DragScrollHandler::onScroll();
}

这将履行合同:实施抽象并使用继承的实施。

但最好的方法(在你的情况下)可能是分离概念并有一个 Scrollable:

class Scrollable {
public: 
  virtual void onScroll()=0;
};

class ListBox: virtual public Scrollable {
public:
  virtual void foo()=0;
};

class DragScrollHandler: virtual public Scrollable {
public:
  void onScroll() override {...}
};

class HorzListBox: public ListBox, public DragScrollHandler {
public:
  void foo() override {...}
};

Any suggestions of a different approach I could use to achieve this functionality?

出于好奇,您可以使用基于 mixin 的方法,如下所示:

struct ListBox {
    virtual ~ListBox() { }
    virtual void onScroll() = 0;
    virtual void foo() = 0;
    virtual void bar() = 0;
};

template<typename T>
struct DragScrollHandler: T {
    void onScroll() override { }
};

template<typename T>
struct HorzListBox: T {
    void foo() override { }
    void bar() override { }
};

int main() {
    ListBox *lb = new HorzListBox<DragScrollHandler<ListBox>>{};
}