我正在尝试为项目创建链接列表。我有这两个文件(一个.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;
};
};
答案 0 :(得分: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
}
在旁注中,您应该缩进在花括号之间放置的代码。它使人类读者更容易将相关元素组合在一起,以及识别代码块。
对于copy c'tor,正如您所看到的,它引用了一个现有对象,并从中构造了一个新对象。编译器提供的defaulut copy c'tor执行浅拷贝。含义为a
且b
为列表,而a.Head
和b.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
,但这是关于名单链接列表的一般想法。
答案 1 :(得分: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
}