将变量设置为类型模板
Setting Variables as Type Template
所以我正在开发一个基于文本的角色扮演游戏,我 运行 遇到了一个问题。我正在研究角色从他们的库存中装备武器的能力。我有类型 Weapon
,它是类型 Item
的子 class;我还有各种其他 class 类型可以存储在玩家的库存中。我现在正在做的是确保玩家想要装备的物品是 Weapon
类型;在此,我正在使用模板(我对使用它还很陌生),因此我有某种通用类型用于测试。代码如下:
template <class T>
void MyCharacter::equipWeapon(){
Weapon testForEquipping;
T chosenWeapon;
chosenWeapon = myInventory.chooseItem();
if(typeid(chosenWeapon).name() == typeid(testForEquipping).name()){
//Haven't added what will happen with this part yet.
}
Weapon tempWeapon1 = equippedWeapon;
Weapon tempWeapon2 = chosenWeapon;
equippedWeapon = tempWeapon2;
chosenWeapon = tempWeapon1;
}
如您所见,我想将 chosenWeapon
设置为等于玩家物品栏中所选的物品; (这部分有效)。但是,问题出在我尝试 运行 程序 error: no matching function for call to 'MyCharacter::equipWeapon()'
中的函数时遇到的这个错误。尽管我研究了这个问题,但我不明白我做错了什么!非常感谢任何帮助或新建议。谢谢!
这需要在运行时完成,因此模板不是使用的正确工具。相反,您应该使用 dynamic_cast
:
void MyCharacter::equipWeapon() {
Item item = myInventory.chooseItem();
if (Weapon* weapon = dynamic_cast<Weapon*>(&item)) {
// Equip the weapon
}
}
使用工厂方法设计模式:
"In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor."
所以我正在开发一个基于文本的角色扮演游戏,我 运行 遇到了一个问题。我正在研究角色从他们的库存中装备武器的能力。我有类型 Weapon
,它是类型 Item
的子 class;我还有各种其他 class 类型可以存储在玩家的库存中。我现在正在做的是确保玩家想要装备的物品是 Weapon
类型;在此,我正在使用模板(我对使用它还很陌生),因此我有某种通用类型用于测试。代码如下:
template <class T>
void MyCharacter::equipWeapon(){
Weapon testForEquipping;
T chosenWeapon;
chosenWeapon = myInventory.chooseItem();
if(typeid(chosenWeapon).name() == typeid(testForEquipping).name()){
//Haven't added what will happen with this part yet.
}
Weapon tempWeapon1 = equippedWeapon;
Weapon tempWeapon2 = chosenWeapon;
equippedWeapon = tempWeapon2;
chosenWeapon = tempWeapon1;
}
如您所见,我想将 chosenWeapon
设置为等于玩家物品栏中所选的物品; (这部分有效)。但是,问题出在我尝试 运行 程序 error: no matching function for call to 'MyCharacter::equipWeapon()'
中的函数时遇到的这个错误。尽管我研究了这个问题,但我不明白我做错了什么!非常感谢任何帮助或新建议。谢谢!
这需要在运行时完成,因此模板不是使用的正确工具。相反,您应该使用 dynamic_cast
:
void MyCharacter::equipWeapon() {
Item item = myInventory.chooseItem();
if (Weapon* weapon = dynamic_cast<Weapon*>(&item)) {
// Equip the weapon
}
}
使用工厂方法设计模式:
"In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor."