【问题标题】:Inherited static method does not use new overridden static attribute继承的静态方法不使用新的重写静态属性
【发布时间】: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


【解决方案1】:

你不能期望静态成员的多态行为。但是由于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'>{};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 2011-04-16
    • 2017-02-07
    • 2011-12-27
    • 2016-10-10
    • 2011-02-14
    • 2011-06-26
    相关资源
    最近更新 更多