使从一个基类派生的类能够使用继承的受保护成员
Make classes derived from one base class able to use inherited protected members
我创建了一个基类,其中包含一个返回对象 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);
}
我个人不会使用尾随返回类型,除非你真的需要它,否则它只会降低可读性。
相关文章:
- 为什么C++需要公共继承,忽略朋友声明,才能使动态向下工作?
- 是否有 C++20 浮点数的包装器,使我能够默认宇宙飞船操作员?
- boost库的哪一部分使cout能够打印wstring以及如何打印?
- 如何使模板化类保留继承?
- 使从一个基类派生的类能够使用继承的受保护成员
- 模板类的专门继承使成员函数返回模板类型,而不是继承的类类型
- 我在 36603 以上输入的任何数组大小时都会返回"堆栈溢出"错误。如何使字符串能够捕获整个.txt文件?
- 如何使继承的类与父类仅在C++中的一个值不同
- 使 C 代码能够作为C++代码运行
- 如何使boost::spirit解析器和lexer能够处理include文件
- 无法使我的getChar()函数能够工作,我希望它能正常工作,输出IS10而不是2 C
- 如何使用模板或继承使以下代码工作
- 如何使C 继承保护访问说明器
- 如何使继承相同基类的类的虚拟方法弄清楚如何处理它们的参数?
- 使代码变小以进行多重继承
- 继承,使基本成员变量const
- 如何使继承的虚函数不可用
- 哪种设计模式可以使继承链中的类更薄
- 如何使继承层次结构中的成员函数始终返回相同的值
- 如何使继承依赖