如何制作由不同子类组成的父类数组

问题描述 投票:0回答:1

我有一个类

Item
,并且从它派生出两个类
Sword
Shield

我希望我的

player
有一系列项目:

class Item
{
    int x;
}

class Sword : public Item
{
     int sharpness = 10;
}

class Shield : public Item
{
    int blockChance = 2;
}

class player 
{
    Item* items[4];
    player()
    {
        items[0] = new Sword;
        items[1] = new Sword;
        items[2] = new Shield;
        items[3] = new Shield;
    }
}

有没有办法可以从

Sword
访问
Shield
items
的值,例如:

items[2]->blockChance;

没有单独的

Sword
Shield
s

数组

这是我第一次使用子类,所以请原谅我愚蠢的问题,并在你的答案中使用简单的词语。

如果这是不可能的,那么我只会有一个单独的数组,但包含两者的单个数组会让这变得更容易

c++ subclass
1个回答
0
投票

有没有办法我可以从物品中访问剑或盾的值

您可以添加一个返回属性值的虚拟方法,如下所示:

class Item
{
    int x;
    public:
    //add this virtual method  
    virtual int GetProperty();
};

class Sword : public Item
{
     int sharpness = 10;
     public:
     //override and return property value
     int GetProperty() override
     {
        return sharpness;  
     }
};

class Shield : public Item
{
    int blockChance = 2; 
    public:
    //override and return property value
    int GetProperty() override
    {
        return blockChance;   
    } 
};

class player 
{   
    Item* items[4];
    player()
    {
        items[0] = new Sword;
        items[1] = new Sword;
        items[2] = new Shield;
        items[3] = new Shield;

        items[0]->GetProperty(); //get values 
    }
};

演示

© www.soinside.com 2019 - 2024. All rights reserved.