0

我有一个类层次结构,其中有一个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'

如果这不起作用,表达上述想法的最佳方式是什么?还有为什么它不起作用?

4

1 回答 1

5

在声明的这两行中DerivedBase被解析为私有继承Base类型,因为它在范围内——即使它是私有的:

explicit Derived(std::unique_ptr<Base> base) : base_{std::move(base)} {}
// ...
std::unique_ptr<Base> base_;

C++ 不会忽略引用当前作用域无权访问的事物的作用域内名称。编译器会在外部范围内查找Base确实可以访问的 a 似乎是合乎逻辑的,但这不是发生的事情。编译器只是停在Base它看到的最接近的位置,而不考虑任何访问修饰符。

Base这可以通过顶级命名空间前缀引用类型来轻松解决::

explicit Derived(std::unique_ptr<::Base> base) : base_{std::move(base)} {}
// ...
std::unique_ptr<::Base> base_;

两者都引用相同的类型,但Derived不能访问继承的Base名称,但可以访问全局Base名称。

您还可以通过重新定义什么Base意思来解决这个问题Derived。在Derived声明的顶部,您可以添加:

protected:
    using Base = ::Base;

这会将继承的名称隐藏在可以访问Base的类型别名后面。Derived

于 2020-06-03T00:36:08.577 回答