我创建了一个基类,其中一个受保护的方法返回对象的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; }
};除了添加next方法之外,还有什么方法可以让它工作吗?
auto getId(const Identifiable& identifiable) const noexcept -> unsigned {
return getId();
}发布于 2018-04-17 12:13:13
不,这不可能。否则,它将允许您通过创建从所讨论的基类派生的另一个类来使用来自任何类的虚拟受保护成员。
发布于 2018-04-17 13:01:49
您不能按预期执行操作,但您可以尝试这样做:
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);
}我个人不会使用拖尾返回类型,除非你真的它,否则它只会降低可读性。
https://stackoverflow.com/questions/49869663
复制相似问题