继承自const类

Mar*_*son 8 c++ inheritance const

我想继承一个类如下的const说明符:

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
};
Run Code Online (Sandbox Code Playgroud)

我的编译器显然const在第二个类声明中给出了关键字的错误.理想情况下,我想避免创建一个新的类ReadOnlyProperty从哪个ConstChild会继承.

我可以以某种方式使用const关键字继承吗?

  • 如果没有,你对如何解决这个问题还有其他想法吗?

Tho*_*ser 7

稍后在继承树中引入可变性并适当地派生:

class Property
{
    int get() const;
};
class MutableProperty : public Property {
{
    void set(int a);
};
Run Code Online (Sandbox Code Playgroud)

然后:

class ConstChild : public Property { ... };
class MutableChild : public MutableProperty { ... };
Run Code Online (Sandbox Code Playgroud)


Jes*_*uhl 0

我想从带有 const 说明符的类继承”

无论你想要多少,都无关紧要。你不能。那不是有效的 C++。

我可以使用 const 关键字进行继承吗?”

不。

  • 对下半场有什么想法,“如果没有,你对如何解决这个问题还有其他想法吗?” (2认同)