c++ - 继承的静态方法不使用新的重写静态属性
问题描述
我在头文件中有一个 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_by
identifier
Component
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
我希望输出是相反的方式。
解决方案
您不能期望静态成员上的多态行为。但作为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'>{};
推荐阅读
- reactjs - ComponentWillReceiveProps 没有被调用
- php - 如何检查一个数字是否在两个数字(或日期)之间?
- android - 为什么 kotlin 活动 xml 没有相关文件
- sql-server - 问题:如何编写命令来查找下订单号为 12345 的客户?
- java - 通过单个连接进行的 JDBC 选择查询是否比包含这些查询的 proc 效率低?
- amazon-web-services - 如何将乐山服务器连接到云(AWS)
- java - 如何将屏幕摆动键盘上的输入文本设置为系统插入符号?
- pyspark - Spark Dataframe 分组和分区,具有一定数量的分区。
- azure - 如何在 Azure 端点上使用 botframework 在您自己的机器人设计中工作?
- hive - 无法对事务表执行更新