C++ 常量函数继承

C++ 常量函数继承,c++,function,constants,C++,Function,Constants,假设我有一个基类foo class foo { virtual int get() const = 0; } 可能还有20个子类foo_1,foo_2。。。继承自foo,形式如下: class foo_1 : public foo { int get() const { return 1; } } ... class foo_20 : public foo { int get() const { return 20; } } 生活突然变得不那么容易了!我有一门课foo

假设我有一个基类foo

class foo {
    virtual int get() const = 0;
}
可能还有20个子类foo_1,foo_2。。。继承自foo,形式如下:

class foo_1 : public foo {
    int get() const { return 1; }
}
...
class foo_20 : public foo {
    int get() const { return 20; }
}
生活突然变得不那么容易了!我有一门课foo_21,必须做到这一点:

class foo_21 : public foo {
    int get() { member_ = false; return 0; }
    bool member_;
}
问题是get在基类中声明为const,我必须更改 子类foo_21中的某些内容。我怎样才能找到绕过它的方法呢?

您的基本函数不是虚拟的,这使得所有这些都是高度推测性的。您的代码应该已经在发布时工作了,尽管可能并不像您预期的那样

您可以使用可变成员:


重要的是可变变量不影响类的逻辑常量。如果需要,您应该重新设计。

您确定需要继承和非虚拟函数隐藏吗?对我来说很有用:注意,我编辑了foo类,因为您错过了虚拟。为了强调这一点,只有当您真正拥有一个只能在运行时确定其具体类型的类层次结构时,才应使用公共继承和虚拟函数。否则,如果您在编译时拥有所有信息,则有更好的技术,例如模板。对不起,基础是虚拟的。。。我修好了that@hate-引擎:只要不尝试实例化foo_21,它就可以编译;但是foo_21::get不会覆盖foo::get。
class foo_21 : public foo
{
    int get() const { member_ = false; return 0; }
    mutable bool member_;
};