Inherit from const class(从 const 类继承)
问题描述
我想从具有 const 说明符的类继承,如下所示:
I would like to inherit from a class with the const specifier like this:
class Property
{
int get() const;
void set(int a);
};
class ConstChild : public const Property
{
// Can never call A::set() with this class, even if
// the instantiation of this class is not const
};
class NonConstChild : public Property
{
// Can call both A::set() and A::get() depending on
// the constness of instantiation of this class
};
我的编译器显然给了我第二个类声明中的 const 关键字的错误.理想情况下,我希望避免创建一个新类 ReadOnlyProperty,ConstChild 将从该类继承.
My compiler obviously gives me an error for the const keyword in the second classes declaration. Ideally I'd like to avoid having to create a new class ReadOnlyProperty from which ConstChild would inherit.
我可以使用 const 关键字进行继承吗?
Can I somehow use the const keyword for inheritance?
- 如果没有,您对如何解决这个问题还有其他想法吗?
推荐答案
稍后在继承树中引入可变性并适当派生:
Introduce mutability later in your inheritance tree and derive appropriately:
class Property
{
int get() const;
};
class MutableProperty : public Property {
{
void set(int a);
};
然后:
class ConstChild : public Property { ... };
class MutableChild : public MutableProperty { ... };
这篇关于从 const 类继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 const 类继承
基础教程推荐
- 提升 ASIO 流缓冲 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- c++ STL设置差异 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
