我有一个类层次结构,其中有一个Base
带有实现列表的基类型和另一个基类,AnotherBase
这几乎是一样Base
的,但有点不同。为了用语言表达这一点,我在第二个基类上使用了私有继承(因此后者的实现与前者的实现之间没有原样的关系)。
假设这是代码(https://wandbox.org/permlink/2e2EG0eKmcLiyvgt)
#include <iostream>
using std::cout;
using std::endl;
class Base {
public:
virtual ~Base() = default;
virtual void foo() = 0;
};
class Impl : public Base {
public:
void foo() {
cout << "Impl::foo()" << endl;
}
};
class AnotherBase : private Base {
public:
using Base::foo;
// other virtual methods
};
class Derived : public AnotherBase {
public:
explicit Derived(std::unique_ptr<Base> base) : base_{std::move(base)} {}
void foo() override {
base_->foo();
}
private:
std::unique_ptr<Base> base_;
};
int main() {
auto impl = std::make_unique<Impl>();
std::make_unique<Derived>(std::move(impl))->foo();
}
当我尝试编译上述代码时,出现以下错误
prog.cc:27:38: error: 'Base' is a private member of 'Base'
如果这不起作用,表达上述想法的最佳方式是什么?还有为什么它不起作用?