[英]C++: Overloads for multiple derived classes within another class
I'm making a text based adventure game (original, I know.) and I hit a problem. 我正在制作一个基于文本的冒险游戏(我知道是原始的),但是遇到了问题。 I want to let the player pick up an item, and then automatically put it where it belongs based on the subclass of
Item
that it belongs to. 我想让玩家拿起一个物品,然后根据它所属的
Item
的子类自动将其放置在其所属的位置。 I have it set up so that when the player types "get " followed by the name of an object in the current room, the following function is called: 我进行了设置,以便当播放器键入“ get”后跟当前房间中对象的名称时,将调用以下功能:
void Game::PickUp(Item * item)
{
m_map.at(m_player.GetLoc())->RemoveItem(item); //Remove item from the room
m_player.AddItem(item); //Add item to the player
}
Within the Player
class I've overloaded AddItem(…)
as follows: 在
Player
类中,我按如下方式重载了AddItem(…)
:
void AddItem(Armor* armor)
{
delete m_armor;
m_armor = armor;
}
void AddItem(Weapon* weapon)
{
delete m_weapon;
m_weapon = weapon;
}
void AddItem(Shield* shield)
{
delete m_shield;
m_shield = shield;
}
void AddItem(Item* item)
{
m_pack.push_back(item);
}
When I run the code, it only calls void AddItem(Item* item)
, which makes sense because that's what's passed into the previous function, but since the object being passed is held in a vector<Item*>
I can't pass it as anything else. 当我运行代码时,它仅调用
void AddItem(Item* item)
,这很有意义,因为这就是传递给上一个函数的内容,但是由于传递的对象保存在vector<Item*>
我无法传递它和其他一样。 Is there a way to detect the subclass of the object being passed and call the correct overload? 有没有办法检测所传递对象的子类并调用正确的重载?
What you're looking for is called multiple dispatch . 您要查找的内容称为多重调度 。 Since the determination of which override is called is made at compile time based on the static type of the parameter, you'll need to call a function that can make use of the run time type of the object to then call back into the original
Player
object. 由于确定哪个覆盖被调用是在编译时根据参数的静态类型确定的,因此您需要调用一个可以利用对象的运行时类型的函数,然后再调用原始的
Player
宾语。
In your Item
base class, you'll declare the base case for this function: 在
Item
基类中,您将声明此函数的基本用例:
virtual void AddToPlayer(Player &player);
It is defined as 定义为
void Item::AddToPlayer(Player &player) {
player.AddItem(*this);
}
This doesn't do anything different than you already have. 这与您已经做的没什么不同。 However, you can add an override of
AddToPlayer
to each class, whose definition is identical to the base class's given above. 但是,您可以向每个类添加
AddToPlayer
的替代,其定义与上面给出的基类相同。 Since the type of *this
will be different in each definition, a different overload of Player::AddItem
will be called. 由于
*this
的类型在每个定义中都不同,因此将调用Player::AddItem
的不同重载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.