我有一个像这样的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
。
答案 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;