【发布时间】:2021-05-12 14:44:13
【问题描述】:
我在头文件中有一个 c++ 类:
class Component {
public:
static const char identifier = '_';
static bool represented_by(const std::string& token_str);
};
represented_by 方法在单独的文件中实现:
bool Component::represented_by(const std::string &token_str) {
return token_str.rfind(identifier, 0) == 0;
}
当我创建Component 的子类的实例并使用覆盖的identifier 值调用represented_by 时,如果输入以为原始Component 类定义的标识符开头,该方法仍然返回true .我怎样才能使它使用identifier 的新值而不是继承的值?
例子:
class Resistor: public Component {
public:
static const char identifier = 'R';
};
输出:
Resistor::represented_by("R1 foo bar 10k")
> 0
Resistor::represented_by("_1 foo bar 10k")
> 1
我希望输出是相反的。
【问题讨论】:
-
常量不“参与”继承,
Resistor中的identifier是与Component中的identifier无关的全新常量。为了得到你想要的,你需要一个返回char并在Component中定义并被覆盖的虚函数。 -
一般情况下不能覆盖成员,只能覆盖方法
标签: c++ inheritance