0

consider these classes (simplified)

class Character 
{
public:
char name[20];
    char type[20];
    int strength;
};

class inventoryItem
{
public:
    char name[20];
};
class weapon: public inventoryItem
{
public:
    int magical resistance;
};
class spell: public inventoryItem
{
public:
   int magical power;
};

i have written a class for a linked list (not allowed to use stl list)

class list
{
public:
struct listItem
{
    listItem* objectPointer;
    listItem* pnext;

}*phead;


list()
{
    phead=NULL;

}

bool isEmpty(){ 
if (!phead)
return true;
else
    return false;
}
void addToBack(listItem *itemtoadd)
{
    listItem *ptemp;
    listItem *ppast;
    listItem *pNewItem;

pNewItem=new listItem();

pNewItem->objectPointer=itemtoadd;
pNewItem->pnext=NULL;
if (phead==NULL)
    phead=itemtoadd;
else
{
      ptemp=phead;
      while(ptemp)
      {
     ptemp= ptemp->pnext;

      }
      ptemp->pnext=itemtoadd;

}

}

};

I have cut this down a lot but my question is , is there an easy way to create linked lists for all these using the same list class ? or am I wasting my time ?

every time I have tried it cant convert the pointer from type 'weapon' to type 'listitem'
I need a list of characters and a list of each weapon or spell for that character
I'm still a beginner with OOP and pointers , the program I have now compiles and I have a list of characters working , however the list is not managed by the class its managed within some other functions, I'm hoping there's a way for one class to deal with it all , can anyone help explain it to me ?

4

3 回答 3

1

看看C++ 模板。使用模板,您可以在读/写代码方面拥有一个列表类,但您可以拥有武器列表、项目列表或任何其他列表,而无需分别编写 WeaponsList、ItemsList 和 SomethingElseList 类。

于 2013-03-24T11:19:17.630 回答
1

简单的答案是这样做

struct listItem
{
    void* objectPointer;
    listItem* pnext;

}*phead;

空指针将允许您存储指向任何内容的指针。当然,这完全取决于您确保您不会忘记您所指向的对象类型。所以这种方法是有风险的。正如建议的那样,更安全的方法是模板。

于 2013-03-24T11:21:16.320 回答
0

你可以使用:

enum item
{
    WEAPON,SPELL
}

class list {
public:
    struct listItem {
        union {
            weapon *weaponPointer;
            spell *spellPointer
        } object;
        item objType;
        listItem* pnext;

    }*phead;

但是问题是您必须访问 type 成员才能确定您正在访问的项目类型。

于 2013-03-24T11:25:47.690 回答