链接列表导致异常,但不确定原因

LinkedList causes exception but not sure why?

本文关键字:不确定 异常 列表 链接      更新时间:2023-10-16

这段代码类似于这里已经有的几篇帖子,但是我遇到了一个独特的问题。链表在尝试插入对象时导致异常。应该有 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;
}

玩家.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&);
};

播放器.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;
}
}

主.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));
}

希望我已经包含了所有内容。我不知道我做错了什么,也不知道该何去何从。

您没有在玩家的构造函数中创建武器对象.cpp:

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

您还可以使武器收集非指针字段对您来说更容易管理。还可以考虑使用 STL 集合而不是您自己的集合(减少出现令人讨厌的异常的风险)...

编辑:是的,黄先生是对的。尝试使用list<Weapon>而不是实现不错的push_frontpush_back方法的LinkedList<Weapon>,也尽量避免使用指针,除非您真正看到它们的使用目的......

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

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

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