首页 文章

可以隐藏C中继承层次结构的一部分吗?

提问于
浏览
11

考虑以下:

B 从类 A 公开继承 . 两者都在库中提供,我无法修改它们 .

我想实现一个派生自 B 的类 Foo ,但我希望允许 Foo 的用户只使用 AFoo 的公共函数(不是来自 B ) . 对于他们来说, FooB 继承是不相关的,这原则上是我无法避免的实现细节 .

因此,原则上我希望 FooA 公开继承,但私下从 B 继承 .

C中是否有一些构造允许我这样做?

我必须补充说,虚拟继承不是一个选项,因为 A ,在我的例子中,派生自 QObject (见Is it safe to use virtual multiple inheritance if QObject is being derived from DIRECTLY?) .

(注意:感兴趣的人:在我的情况下, AQWindowBQt3DExtras::Qt3DWindow

2 回答

  • 2

    你在c中最接近的是:

    class Foo : private B {
      public:
        using A::foo; // Expose function foo in Foo's API.
        using A::bar;
        operator A&() { return *this; } // Implicit conversion to `A` when needed.
        operator A const&() const { return *this; }
    };
    
  • 9

    由于这是Qt,我认为这是你能做的最接近的:

    struct Foo : A {
        // override all function of A, forward its to B
    private:
        B b; // or pointer to B, it's depend on your design
    };
    

相关问题