-1

我正在尝试为项目创建链接列表。我有这两个文件(一个.h 和一个.cpp)。我不确定如何制作一个复制构造函数,所以我不确定这是否与它有关。我想如果有人也想指出我正确的方向,那会很有帮助。谢谢你。

#include <iostream>
#include "studentList.h"

using namespace std;

// Default Constructor for StudentList
// Creates Dummy Head Node for a new empty list
StudentList::StudentList ()
{
// Create the dummy head node
Node* Head;             // Creates Head Node
Head = new Node;        
Head->next = NULL;      // Sets pointer to NULL by default
}

//Copy Constructor
StudentList::StudentList(const StudentList& list)
{

}

void StudentList::addStudentList(Student newStudent)
{

在这里得到错误!!!!!!

if (Head->next == NULL)
{
    Head->next->student = newStudent;
    Head->next->prev = Head;
    Head->next->next = NULL;
}
}

这是.h文件

#include <iostream>
#include "Student.h"

using namespace std;


class StudentList{

public:
//Default Constructor
StudentList();
//Copy Constructor
StudentList(const StudentList& list);
//Add Student Method
void addStudentList(Student);


private:
// Node struct to hold Student data and with pointers to a previous and next node in linked list
struct Node {
Student student;
Node* prev;
Node* next;
};

};
4

2 回答 2

3

Head应该是会员。您创建的指针Head具有自动存储功能。当构造函数完成时,它会超出范围,并且您会得到一个悬空引用。

class StudentList{

public:
//Default Constructor
  StudentList();
//Copy Constructor
  StudentList(const StudentList& list);
//Add Student Method
  void addStudentList(Student);


private:
// Node struct to hold Student data and with pointers to a previous and next node in linked list
  struct Node {
    Student student;
    Node* prev;
    Node* next;
  };

  Node* Head;

};


StudentList::StudentList ()
{
  Head = new Node;        
  Head->next = NULL;      // Sets pointer to NULL by default
}

附带说明一下,您应该缩进放在花括号之间的代码。它使人类读者更容易将相关元素组合在一起,从而发现代码块。

至于复制 c'tor,如您所见,它采用对现有对象的引用,并从中构造一个新对象。编译器提供的默认复制 c'tor 执行浅复制。含义是ab是列表,比a.Headb.Head指向相同的起始元素。您可以使用以下内容覆盖它以进行深层复制:

StudentList::StudentList(const StudentList& list)
{
  Node* Head = new Node;
  Node* tmp = Head;
  Node* iter = list.Head;
  while (iter)
  {
    *tmp = *iter;
    tmp->next = NULL;
    if (iter->next)
      tmp->next = new Node;
    tmp = tmp->next;
    iter = iter->next;
  }
}

我当然忽略了tmp->prev,但这是符号链表的一般想法。

于 2013-02-02T18:20:22.570 回答
1

这里

StudentList::StudentList ()
{
// Create the dummy head node
Node* Head;             // Creates Head Node
Head = new Node;        
Head->next = NULL;      // Sets pointer to NULL by default
}

正在构造 ctor 中的局部变量,该变量在构造 StudentList 后不再存在。您需要将其移出以Head使其成为类成员,即在头文件中声明它

class StudentList {
..
Node* Head;
};

所以你的构造函数看起来像

StudentList::StudentList ()
{
// Create the dummy head node
Head = new Node;        
Head->next = NULL;      // Sets pointer to NULL by default
}
于 2013-02-02T18:20:51.727 回答