我正在开发一个涉及类继承和函数参数重载的C++项目。我有两个基类,永远不应该实例化而只能继承:
class Item {
// "data" class
}
class Evaluator {
int get_val(Item item) {}
}
所以这些可以继承:
class ItemSword : Item {}
class ItemPickaxe : Item {}
class EvaluatorZombie : Evaluator {
int get_val(ItemSword& item) {}
}
这里我想要,当我写
EvaluatorZombie().get_val(std::make_unique<ItemSword> item)
时,我希望它使用get_val
中实现的EvaluatorZombie
。但如果我要写 EvaluatorZombie().get_val(std::make_unique<ItemPickaxe> item)
,我希望它使用默认的 Evaluator get_val
,因为这个 Item 没有在 EvaluatorZombie 中实现。
特定项目“类型”可能不同,并且在编译时未知,所以我意识到这可能是一个问题。
我见过的所有解决方案都需要在评估器中的单个“get_val”方法中实现所有“项目”,但我希望能够为评估器子类中的不同项目实现多个“get_vals”,然后使用当 Item 未在 get_val 中实现时默认。
所以我想要一个解决方案:
任何帮助或想法表示感谢,谢谢。
将
Evaluator::get_val()
设为 virtual
,以便 EvaluatorZombie
可以覆盖它,然后使用 dynamic_cast
来测试传递的 Item
是否是特定的派生类型。 例如:
class Item {
public:
virtual ~Item() = default;
};
class Evaluator {
public:
virtual ~Evaluator() = default;
virtual int get_val(Item& item) { return 0; }
}
class ItemSword : public Item {};
class ItemPickaxe : public Item {};
class EvaluatorZombie : public Evaluator {
public:
int get_val(Item& item) {
ItemSword *sword = dynamic_cast<ItemSword*>(&item);
if (sword) {
// use sword as needed ...
return ...;
}
return Evaluator::get_val(item);
}
};
EvaluatorZombie{}.get_val(ItemSword{});
// or:
EvaluatorZombie{}.get_val(*std::make_unique<ItemSword>());