带有父子参数的 C++ 函数参数重载

问题描述 投票:0回答:1

我正在开发一个涉及类继承和函数参数重载的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 中实现时默认。

所以我想要一个解决方案:

  1. 允许我在每个 Item 类的 Evaluator 子级中编写多个 get_vals
  2. 不修改原有的“Item”和“Evaluator”,或者至少做到最低限度。我希望最初的“项目”和“评估者”对孩子们来说是不可知的。

任何帮助或想法表示感谢,谢谢。

c++ function overloading
1个回答
0
投票

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>());
© www.soinside.com 2019 - 2024. All rights reserved.