5

我的代码中有一个相对复杂的接口,并且想将部分实现委托给另一个类,而无需在实现中编写大量转发函数。请参阅此简化的示例代码:

#include <stdio.h>

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

struct Delegate {
    virtual void foo()
    { printf("foo\n"); }
};


struct Impl : public Interface, private Delegate {
    // delegate foo to Delegate
    using Delegate::foo;

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

int main() {
    Interface* i = new Impl();
    i->foo();
    i->bar();
    delete i;
    return 0;
}

现在 G++ 抱怨foo没有在 Impl 中实现。然而,Impl 中有一个非常好的函数foo,它只是取自另一个父类。为什么编译器不能正确填写 vtable?

(注意:我知道在这个特定的示例中,Delegate 可以从 Interface 派生。我想了解是否可以委托功能而不必从接口派生委托。)

4

0 回答 0