gpt4 book ai didi

c++ - C++中不同对象的多个链表

转载 作者:行者123 更新时间:2023-11-28 03:20:25 24 4
gpt4 key购买 nike

考虑这些类(简化)

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;
};

我写了一个链表的类(不允许使用STL列表)

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;

}

}

};

我已经减少了很多,但我的问题是,是否有一种简单的方法可以使用相同的列表类为所有这些创建链接列表?还是我在浪费时间?

每次我都尝试过,它无法将指针从“weapon”类型转换为“listitem”类型
我需要一个角色列表以及该角色的每种武器或法术的列表
我仍然是 OOP 和指针的初学者,我现在编译的程序并且我有一个工作字符列表,但是该列表不是由它在其他一些函数中管理的类管理的,我希望有一种方法可以让一个类来处理这一切,任何人都可以帮忙给我解释一下?

最佳答案

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

关于c++ - C++中不同对象的多个链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15597724/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com