我的一个作业有问题。我需要做一个链表连接,但重新定义运算符+后,我有分割错误。下面是代码:
在main.cpp:case CONCAT:
do
{
std::cout << "Which two list do you want to concat?(1-3) ";
std::cin >> s;
std::cin >> g;
selectedlist =atoi(s.c_str());
selectedlist2 =atoi(g.c_str());
} while ((
selectedlist== 0 &&
s != "0" &&
(selectedlist > 3 || selectedlist < 1)
) &&
(
selectedlist2== 0 &&
g != "0" &&
(selectedlist2 > 3 || selectedlist2 < 1)
)
);
Lista[selectedlist-1]+Lista[selectedlist2-1];
std::cout<<"Ready";
break;
头文件:
class lista
{
public:
enum Exceptions{EMPTY};
lista() : first(NULL),last(NULL),current(NULL){ first = new Elem(0,0);}
virtual ~lista();
lista(const lista& s);
int Current() const {return current->Adat;}
void First() {current = first->next;}
bool End() const {return current==NULL;}
void Next() {current = current->next;}
void Vegere(int e);
void Elejerol();
bool Urese();
int Eleje();
friend std::ostream& operator<<(std::ostream& s, const lista& a);
friend lista operator+(lista& a, lista& b);
private:
struct Elem{
int Adat;
Elem* next;
Elem(int c, Elem* n): Adat(c), next(n){};
};
Elem* first;
Elem* last;
Elem* current;
};
在list .cpp:
lista operator+(lista& a, lista& b)
{
if(b.first->next!=NULL && a.first->next!=NULL)
{
a.last->next = b.first->next;
a.last = b.last;
b.first = new lista::Elem(0,0);
b.last = NULL;
b.current = NULL;
}
else
{
throw lista::EMPTY;
}
return a;
}
void lista::Vegere(int e) {
Elem* p = new Elem(e,0);
if(last==NULL) {
first -> next = p;
last = p;
}
else {
last -> next = p;
last = p;
}
}
它抱怨,所有其他函数(空,加数字等)工作正常。我做错了什么?
void lista::Vegere(int e)
{
Elem* p = new Elem(e,0);
if(last==NULL)
{
first -> next = p; last = p;
}
else
{
last -> next = p; last = p;
}
}
析构函数:
lista::~lista()
{
Elem *p, *v;
p = first;
v = first -> next;
while( v!=NULL)
{
delete p;
p = v;
v = v -> next;
}
delete p;
}
我已经弄明白了。我没有在这里发布这部分代码,但经过一些调试后,我得到了它。错误如下:
lista::lista(const lista& s){
if(s.first->next==NULL)
{
first->next = last = NULL;
}
else
{
Elem* q = new Elem(s.first->Adat,NULL);
first = q;
for(Elem* p=s.first->next;p!=NULL;p=p->next)
{
q = new Elem(p->Adat,NULL);
q->next = q;
}
last = q;
}
current = first;
THIS PART is the error:
[
while(current!=NULL && current->Adat!=s.current->Adat)
{
current=current->next;
}
]
}
我刚把它删除了,它还能用。:)
问题是
lista operator+(lista& a, lista& b)
{
...
return a;
}
这将创建a
的副本,然后立即销毁(因为您不会将其保存在任何地方)。您没有定义复制构造函数,所以您使用编译器定义的构造函数(它只是复制指针)。临时函数的析构函数会删除a.first
所指向的内存,然后当你调用a
的析构函数时,一切都会爆炸。
如果析构函数正在释放内存,则需要声明复制构造函数和复制赋值操作符。最简单的定义是删除它们(以= delete;
结尾)-然后您需要更改operator +
的定义(可能通过将函数名称更改为append()
)。