首页 > 解决方案 > 继承的静态方法不使用新的重写静态属性

问题描述

我在头文件中有一个 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调用时,如果输入以为原始类定义的标识符开头,该方法仍然只返回 true 。我怎样才能使它使用新值而不是继承值?represented_byidentifierComponentidentifier

例子:

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

我希望输出是相反的方式。

标签: c++inheritance

解决方案


您不能期望静态成员上的多态行为。但作为char一个整体类型,您可以使用模板:

template <char Identifier = '_'>
class Component {
public:
    static const char identifier = Identifier;
    static bool represented_by(const std::string& token_str);
};

template <char Identifier>
bool Component<Identifier>::represented_by(const std::string &token_str) {
    return token_str.rfind(identifier, 0) == 0;
}

class Resistor: public Component<'R'>{};

推荐阅读