簡體   English   中英

如何在變量中存儲不同的類?

[英]How to store different classes in a variable?

class Resources{

protected:
    int size;
    char repchar;   //Representing Char
public:
    Resources(int size=0,char repchar=' ');
    char getchar();
    int getsize();
        //copy const
        //destructor };


class Bone:public Resources{
private:
    int BoneScore;
public:
    Bone(int size,char repchar,int BoneScore);
};


class Trap:public Resources{
/*  private:
          bool active=false;*/
    public:
        Trap();
     //   bool activehigh();
        };
class Food:public Resources{
    private:
        int energy;
    public:
        Food(int size,char repchar,int energy);
};


class Water:public Resources{
    private:
        int energy;
    public:
        Water();
};

大家好,基本上我是C++的初學者。我正在嘗試創建一個基於地圖的游戲。我將隨機放置資源到map,然后他們將輪流收集。最后,程序將計算積分來自骨頭,並決定獲勝者。因此,我想存儲玩家獲取的資源。我的意思是我想將不同的類存儲在一個變量中。感謝您提前提供幫助。我有 4 個不同的資源骨頭,陷阱,水,食物。

這稱為多態性:

class base {};
class child1 : public base{};
class child2 : public base{};


base* b1 = new child1();
base* b2 = new child2();

將我的base class 視為您的Resource class。 你可以這樣做:

typedef std::list<Resource*> Resources;


Resources resources;

// Map setup
resources.push_back(new Bone());
resources.push_back(new Trap());
resources.push_back(new Water());

// Interact with each one:
for(auto& resource : resources)
    resource->getsize(); // Call a method from Resource::

// Interact with traps:
for(auto& resource : resources)
    if (resource->getchar() == 't') // If the resource is a trap
        dynamic_cast<Trap*>(resource)->trigger(); // Trap-specific method  

// clean-up
for(auto it = resources.begin(); it != resources.end(); )
{
    delete *it;
    it = resources.erase(it);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM