使从一个基类派生的类能够使用继承的受保护成员

Make classes derived from one base class able to use inherited protected members

本文关键字:能够使 继承 成员 受保护 派生 基类 一个      更新时间:2023-10-16

我创建了一个基类,其中包含一个返回对象 id 的受保护方法。我希望只有派生类能够在其他派生类上查询此 id,但对继承层次结构之外的类隐藏它。

class Identifiable {
    public:
        virtual ~Identifiable() = default;
    protected:
        virtual auto getId() const noexcept -> unsigned = 0;
    };
    class ObjectA: public Identifiable {
    protected:
        auto getId() const noexcept -> unsigned override { return 0; }
    };
    class SpecificObjectA: public ObjectA {
    protected:
        using ObjectA::getId;
    };
    class ObjectB: Identifiable {
    public:
        explicit ObjectB(const SpecificObjectA& objectA) {
            objectA.getId(); // error C2248: 'SpecificObjectA::getId': cannot access protected member declared in class 'SpecificObjectA'
        }
    protected:
        auto getId() const noexcept -> unsigned override { return 0; }
};

除了添加下一个方法之外,还有什么方法可以使其工作吗?

auto getId(const Identifiable& identifiable) const noexcept -> unsigned {
    return getId();
}

不,这是不可能的。否则,它将允许您通过创建从相关基类派生的另一个类来使用任何类中的虚拟受保护成员。

您无法按预期执行,但可以尝试以下操作:

class Identifiable
{
public:
    virtual ~Identifiable() = default;
protected:
    virtual unsigned getId() const noexcept = 0;
    static unsigned int getId(Identifiable const& other)
    {
        return other.getId();
    }
};

现在您可以执行以下操作:

explicit ObjectB(const SpecificObjectA& objectA)
{
    Identifiable::getId(objectA);
}

我个人不会使用尾随返回类型,除非你真的需要它,否则它只会降低可读性。