继承自const类 [英] Inherit from const class

查看:204
本文介绍了继承自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类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆