手写链表是segfaulting,我不明白为什么 [英] Handwritten linked list is segfaulting and I don't understand why
问题描述
您好,我是一个有趣的工作,使一个接口从c ++运行gnuplot,并且由于某种原因我的链表的实现失败。
Hi I was working on a bit of fun, making an interface to run gnuplot from within c++, and for some reason the my linked list implementation fails.
下面的代码在 plots-> append(&plot)
行上失败。通过代码我发现由于某种原因,析构函数〜John()
在构造函数 John()
The code below fails on the line plots->append(&plot)
. Stepping through the code I discovered that for some reason the destructor ~John()
is called immediately after the constructor John()
, and I cannot seem to figure out why.
下面的代码是一个只能在 Plot *
。最初我把链表作为模板类。并且它工作正常为 ll< int>
和 ll< char *>
,但由于某种原因,它失败,因为 ll
。
The code included below is a stripped down version operating only on Plot*
. Originally I made the linked list as a template class. And it worked fine as ll<int>
and ll<char*>
but for some reason it fails as ll<Plot*>
.
请帮我找出为什么会失败?
Could youp please help me figure out why it fails? and perhaps help me understand how to make it work?
提前:感谢一堆!
//可以帮助我理解如何使它工作吗? B2S
//B2S
#include <string.h>
class Plot{
char title[80];
public:
Plot(){ }
};
class Link{
Plot* element;
Link* next;
Link* prev;
friend class ll;
};
class ll{
Link* head;
Link* tail;
public:
ll(){
head = tail = new Link();
head->prev = tail->prev = head->next = tail->next = head;
}
~ll(){
while (head!=tail){
tail = tail->prev;
delete tail->next;
}
delete head;
}
void append(Plot* element){
tail->element = element;
tail->next = new Link();
tail->next->prev = tail;
tail->next = tail;
}
};
class John{
ll* plots;
public:
John(){
plots= new ll();
}
~John(){
delete plots;
}
John(Plot* plot){
John();
plots->append(plot);
}
};
int main(){
Plot p;
John k(&p);
}
推荐答案
>
The statement:
John();
只是构造一个新的无名约翰,创建并立即销毁。没有办法(在当前版本的C ++中)从另一个构造函数或已经构造的对象调用构造函数。
Just constructs a new nameless John which is created and immediately destroyed. There is no way (in the current version of C++) to call a constructor from another constructor or on an already constructed object.
这意味着图
成员
k
从未被初始化,您从 John
构造函数中调用 append
。
This means that the plots
member of your John
called k
is never being initalized, hence the crash when you call append
from the John
constructor.
正如Neil Butterworth所说,如果你实际上构造了一个 ll
实例,还有其他问题,这只是最直接的问题。]
[As Neil Butterworth comments, if you had actually constructed an ll
instance there are other issues with it, this is just the most immediate problem.]
这篇关于手写链表是segfaulting,我不明白为什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!