我正在尝试用 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()
。
我应该如何修改我的代码?或者有什么设计模式可以参考吗?
问题是
FooBar
没有实现foo
中的抽象方法FooInterface
。
如果添加它,代码将编译:
class FooBar : public Foo, public FooBarInterface {
public:
void foo() override {}; // <-- add this
void bar() override {};
};