C ++重写继承的静态const变量的值

时间:2017-10-19 21:54:29

标签: c++

我有一个像这样的cpp类:

class A{
    protected:
      static const int _a = 0, _b = 0, _c = 0;
      std::string _data;
    public:
      void myMethod(); //method that changes _data based on the value of _a, _b and _c
};

如果我想创建让我们说:

Class B : public A{};

如何更改_a_b_c的值以更改myMethod的行为?即使我再次声明它们,myMethod仍会使用class A代替class B的值。

如果我想更改这3个数字,是否需要覆盖整个myMethod功能?

编辑:myMethod()public,而不是private

2 个答案:

答案 0 :(得分:1)

您无法直接更改const静态成员,但也许您想要的是virtual getA(), getB(), getC()方法。

然后,您的A::myMethod()实现使用getter而不是直接访问静态成员。

B课程中,您可以覆盖get方法以返回不同的值(可能从新声明的静态或任何有意义的内容中读取),然后A::myMethod()会自动选择它们起来。

答案 1 :(得分:0)

您不能更改常量的值作为名称const。你只能初始化它们。

class A{
    protected:
        static const int val1, val2, val3;
    public:
        void myMethod();
};

const int A::val1 = 9;
const int A::val2 = 5;
const int A::val3 = 4;