cpp 中的接口

Interfaces in cpp

您很快就会看到,我不是 C++ 开发人员,对于这个问题,我使用 C++ 是我唯一的选择。我不介意学习,所以只是一些指导将不胜感激。

我有一个面板class如下:

class Panel {
    ...  // Methods that implement Panel
    virtual void draw() = 0;
    ...  // Other methods to implement Panel
}

我想要它的两个变体,所以我创建了两个接口

class Foo {
    virtual void foo() = 0;
}

class Bar: public Foo {
    virtual void bar() = 0;
}

我想将 Foo 的实现 class 传递给其他 classes 并且让它们只能调用方法 foo,Bar 也是如此。

在其他语言中,我可以创建实现 Foo 的 class:

class FooPanel : public Panel,  implements Foo{ ... }

class BarPanel : public Panel, implments Bar { ... }

然后我可以传入一个方法:

//method(..., foo* pFoo, ...);  the signature
  method(..., (Foo*)&barPanel, ...);

我认为在 C++ 中实现此目的的唯一方法是:

class FooPanel : public Panel {
    virtual void foo() = 0;
}

然后必须传递整个面板,实现者才能调用面板方法。

我在哪里可以了解如何做到这一点?

其他语言(如java)所说的“接口”只是C++中的抽象基础class。因此,如果您只是将 implements 关键字替换为 public virtual,它将按您预期的那样工作:

class FooPanel : public Panel, public virtual Foo { ... }

class BarPanel : public Panel, public virtual Bar { ... }