我目前正在制作一个 2D 平台游戏引擎,但我似乎无法为我的“项目”类创建一个优雅的设计。
我所说的元素是什么意思:玩家可以在他/她的库存中持有的任何东西,例如。铁或治疗药水
它如何适合我的项目 - 3 个类处理“项目”:
#include "Globals.h"
#include "Item.h"
class Player_Equipment_Slots
{
public:
Player_Equipment_Slots();
Player_Equipment_Slots(Player& playerObj);
virtual ~Player_Equipment_Slots();
// return: the item that was already equipped, if there was one already equipped
Item equipItem(Item itemToEquip);
Attributes getTotalAttributes() const { return totalAttributes; }
private:
// applies passive effects equipment may have to the player and removes any existing one (called by equipItem)
void updateEquipmentEffects(Item& newEquipment, Item& oldEquipment);
// subtracts the stats of the old item and adds the new items stats (called by equipItem)
void updateTotalAttributes();
Item necklaceSlot;
Item ringSlot1;
Item ringSlot2;
Item trinket1;
Item trinket2;
Attributes totalAttributes;
Player& playerObj;
};
问题:Item 类有两个构造函数
ItemDetails();
ItemDetails(std::string itemName, itemType itmType, rarity itemRarity, Coordinate itemIconCoord, std::string effect);
理想情况下,我希望摆脱默认构造函数,因为只能使用第二个构造函数创建项目,但是如果我这样做,Player_Equipment_Slots 类将在编译时提示可以理解,因为 -
Item necklaceSlot;
Item ringSlot1;
Item ringSlot2;
Item trinket1;
Item trinket2;
对象需要调用默认构造函数。
问题 :我将如何重新设计这些类,以便我的 Item 类没有默认构造函数,但其他类(例如 Player_Equipment_Slots)可以存储私有(private) Item 对象。
我知道这可以通过指针轻松实现,但是我想避免在每次创建新项目时都使用“new”关键字。也许还有一种方法可以在不使用“new”关键字的情况下使用指针,但是我不确定如何实现它。
最佳答案
使用继承,Item 用于不同的使用类(只是一个建议),如果您不想使用默认构造函数,只需将其删除 Item()=delete
或输入 私有(private) 类的部分。
关于C++:如何正确设置 "Item"类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52548065/