[英]Make classes derived from one base class able to use inherited protected members
I created a base class with one protected method returning the id of the object.我创建了一个基类,其中一个受保护的方法返回对象的 id。 I want only derived classes to be able to query this id on other derived classes, but hide it from classes outside the inheritance hierarchy.
我只希望派生类能够在其他派生类上查询此 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; }
};
Is there any way to make it work other than adding a next method?除了添加下一个方法之外,还有什么方法可以使它工作吗?
auto getId(const Identifiable& identifiable) const noexcept -> unsigned {
return getId();
}
No, that's not possible.不,那不可能。 Otherwise, it would let you use virtual protected members from any class by creating another class derived from the base class in question.
否则,它会让您通过创建从相关基类派生的另一个类来使用来自任何类的虚拟受保护成员。
You cannot do as intended, but you might try this:你不能按预期做,但你可以试试这个:
class Identifiable
{
public:
virtual ~Identifiable() = default;
protected:
virtual unsigned getId() const noexcept = 0;
static unsigned int getId(Identifiable const& other)
{
return other.getId();
}
};
Now you can do:现在你可以这样做:
explicit ObjectB(const SpecificObjectA& objectA)
{
Identifiable::getId(objectA);
}
I personally wouldn't use trailing return type unless you really need it, otherwise it just reduces readability.我个人不会使用尾随返回类型,除非你真的需要它,否则它只会降低可读性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.