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

标签 c++ game-engine

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

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

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

    最佳答案

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

    关于C++:如何正确设置 "Item"类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52548065/

    相关文章:

    c++ - 具有极其简单类的未解析外部符号(VS2010)

    c++ - friend 混入模板?

    c# - 在应用程序中创建自动化宏支持

    swift - 动态 View 取决于自由形式移动的 View 数量

    architecture - MonoGame - 项目布局和结构(架构)

    c++ - "inherit"另一个关系 (1 :N) relationship

    c++ - Qt 我应该从 QDataStream 派生吗?

    c++ - 在 C++ 中构造左填充的 NULL 固定长度字符数组的最有效方法是什么?

    java - 在不阻塞游戏线程的情况下等待触摸输入

    Java-创建瓦片 map gif