【发布时间】:2009-12-09 21:00:39
【问题描述】:
我的大脑从来没有真正理解过链表和指针的细微之处,但我正在尝试帮助一位朋友完成一些 C++ 作业。 (在我走得更远之前,是的,有 std::list 但我正在寻找一个学术答案,也许能让他和我更容易理解链表)。
我们需要做的是根据用户输入生成一个对象链表(Employee 对象),然后将该信息显示给用户。每当我尝试将对象分配到链接列表容器中时,它都会出现段错误。
我有以下链表对象:
class LinkedListContainer {
private:
Employee *emp;
LinkedListContainer *next;
public:
Employee getEmployee() { return *emp; }
void setEmployee(Employee *newEmp) {
*emp = *newEmp // This is what is causing the segfault
}
LinkedListContainer getNext() { return *next; }
void setNext(LinkedListContainer *newContainer) {
*next = *newContainer;
}
}
我确定我做错了什么。
【问题讨论】:
-
次要的挑剔,不是答案:
getEmployee()应该返回Employee&而不是Employee。前者是引用,后者将Employee复制到堆栈中。getNext()有同样的问题;它会复制下一个 LinkedListContainer 对象,如果您必须处理复制构造函数,这可能会造成混乱。
标签: c++ pointers segmentation-fault