C++:如何正确设置 "Item" 类



我目前正在制作一个2D平台游戏引擎,但我似乎无法为我的"Item"类创建一个优雅的设计。

我所说的物品是什么意思:玩家可以在他/她的物品栏中持有的任何东西,例如铁或治疗药水

它如何适应我的项目 - 3 个类处理"项目":

  1. "库存"类

  2. "Level"类(存储掉落的"项目"的位置(

  3. "Player_Equipment_Slots"类。这是问题出现的地方:

    #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(可以存储私有 Item 对象。 我知道这可以通过指针轻松实现,但是我想避免在每次创建新项目时使用"new"关键字。也许还有一种方法可以在不使用"new"关键字的情况下使用指针,但我不确定如何实现它。

使用继承,该项目适用于不同的使用类(只是一个建议(,如果您不想使用默认构造函数,只需将其删除Item()=delete或放在类的私有部分中。

最新更新