C++ 多重继承:实现具有重叠虚函数的接口

问题描述 投票:0回答:1

我正在尝试用 C++ 设计一个类层次结构,其中有一个带有纯虚函数

FooInterface
的基接口
foo()
,以及另一个应该扩展
FooBarInterface
并添加附加函数
FooInterface
的接口
bar()
。然后,我有一个从
Foo
实现
foo()
的类
FooInterface
,以及继承自
FooBar
Foo
并实现
FooBarInterface
的类
bar()
。 我的目标是让
func
函数接受 std::shared_ptr 到任何同时实现
foo()
bar()
的对象。

#include <memory>

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

class FooBarInterface : public FooInterface {
public:
    virtual void bar() = 0;
};

class Foo : public FooInterface {
public:
    void foo() override {};
};

class FooBar : public Foo, public FooBarInterface {
public:
    void bar() override {};
};

void func(std::shared_ptr<FooBarInterface> fb) {}

int main() {
    func(std::make_shared<FooBar>());
}

注意:省略虚拟析构函数。

但是,此代码无法编译,可能是因为

foo()
中的
FooBarInterface
并未在
FooBar
中被覆盖,即使
FooBar
继承自实现
Foo
foo()

我应该如何修改我的代码?或者有什么设计模式可以参考吗?

c++ oop polymorphism multiple-inheritance
1个回答
0
投票

问题是

FooBar
没有实现
foo
中的抽象方法
FooInterface

如果添加它,代码将编译:

class FooBar : public Foo, public FooBarInterface {
public:
    void foo() override {};   // <-- add this
    void bar() override {};
};
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.