从抽象基类的多个部分实现继承?

Ste*_*mer 13 c++ multiple-inheritance virtual-inheritance

是否有可能有一些抽象接口的部分实现,然后通过使用多个继承这些部分实现收集到一个具体的类中

我有以下示例代码:

#include <iostream>

struct Base
{
    virtual void F1() = 0;
    virtual void F2() = 0;
};

struct D1 : Base
{
    void F1() override { std::cout << __func__ << std::endl; }
};

struct D2 : Base
{
    void F2() override { std::cout << __func__ << std::endl; }
};

// collection of the two partial implementations to form the concrete implementation
struct Deriv : D1, D2
{
    using D1::F1; // I added these using clauses when it first didn't compile - they don't help
    using D2::F2;
};

int main()
{
    Deriv d;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

无法编译时出现以下错误:

main.cpp: In function ‘int main()’:
main.cpp:27:11: error: cannot declare variable ‘d’ to be of abstract type ‘Deriv’
main.cpp:19:8: note:   because the following virtual functions are pure within ‘Deriv’:
main.cpp:5:18: note:    virtual void Base::F1()
main.cpp:6:18: note:    virtual void Base::F2()
Run Code Online (Sandbox Code Playgroud)

jua*_*nza 10

尝试几乎继承Base:

struct D1 : virtual Base
{
    void F1() override { std::cout << __func__ << std::endl; }
};

struct D2 : virtual Base
{
    void F2() override { std::cout << __func__ << std::endl; }
};
Run Code Online (Sandbox Code Playgroud)

如果没有虚拟继承,你的多重继承的场景看起来像两个独立的和不完整的基类继承D1D2,这两者都不可以被实例化.