LinkedList 导致异常但不确定为什么?

LinkedList causes exception but not sure why?

此代码与此处已有的几篇文章类似,但我遇到了一个独特的问题。链接列表在尝试插入对象时导致异常。应该有 5 名玩家,每名玩家拥有不同数量的武器,每件武器都有不同的轮数。我不知所措。请帮忙!

LinkedList.h

template <class T>
class LinkedList {
public:
 T *first;
 LinkedList();
 ~LinkedList();
 inline bool IsEmpty();
 inline void Insert(T *);
 void Display()const; 
 T *Find(const int key)const; 
 T *Delete(); 
 T *Delete(const int key); 
};

template <class T>
LinkedList<T>::LinkedList(){
      first = 0;
}

template <class T>
LinkedList<T>::~LinkedList(){

}

template <class T>
bool LinkedList<T>::IsEmpty(){
     return (first == 0);
}

template <class T>
void LinkedList<T>::Insert(T * newLink){
     newLink->next = first; //exception break highlights here
     first = newLink;
}

template <class T>
void LinkedList<T>::Display()const {
               T *current = first;
               while (current != 0) {
                 current->Display();
                 current = current->next;
               }
}

template <class T>
T *LinkedList<T>::Find(const int key)const {
               T *current = first;
               while (current->data != key){
                  if (current->next == 0)
                      return 0;
                  else
                      current = current->next;
               }
               return current;
}

template <class T>
T *LinkedList<T>::Delete() {
              T *temp = first;
              first = first->next;
              return temp;
}

Player.h

class Player:public GameObject
{
public:
Player* leftChild;
Player* rightChild;
LinkedList<Weapon>* weapons;
Player();
~Player();
void Display();
bool operator != (const Player&);
bool operator <(const Player&);
};

Player.cpp

Player::Player()
{
leftChild = 0;
rightChild = 0;
}

Player::~Player()
{
}

void Player::Display()
{
}

bool Player::operator<(const Player& player)
{
if (this->instances < player.instances)
{
    return true;
}
else
{
    return false;
}
}

bool Player::operator!=(const Player& player)
{
if (instances == NULL)
{
    return false;
}
else
{
    return true;
}
}

Main.cpp

int main()
{   
Player *players[4];
players[0] = new Player();
players[1] = new Player();
players[2] = new Player();
players[3] = new Player();
players[4] = new Player();
players[0]->weapons->Insert(new Weapon(1));
}

希望我已经包含了所有内容。我不知道我做错了什么,或者从这里去哪里。

您没有在 Player.cpp 的构造函数中创建武器 object:

Player::Player()
{
    leftChild = 0;
    rightChild = 0;
    weapons = new LinkedList<Weapon>;
}

你也可以把武器collectionnon-pointer字段做成你管理起来更方便。还可以考虑使用 STL collection 而不是您自己的(出现严重异常的风险较小)...

编辑: 是的,黄先生是对的。尝试使用 list<Weapon> 而不是你的 LinkedList<Weapon> 它实现了很好的 push_frontpush_back 方法,也尽量避免使用指针,除非你真的明白它们的使用目的......

您还需要分配 weapons。例如在 Player() 构造函数中:

Player::Player() {
    leftChild = 0;
    rightChild = 0;
    weapons = new LinkedList<Weapon>;
}

否则players[0]->weapons指向无效指针,导致异常