我的老师要求写一个模板类列表(就像在STL中一样) 我的代码编译但它会崩溃,但我找不到原因,有人可以试着帮我吗? 我想可能有两个参数的构造函数有问题吗?
-----Main.cpp------
#include "Liste.h"
#include <iostream>
int main()
{
Liste<int> l ;
int x = 5 ;
int y = 6 ;
int z = 7 ;
l.insert_first(y) ;
l.insert_first(x) ;
l.insert_last(z) ;
std::cout << l << std::endl ;
}
-----Liste.h------
#pragma once
#include <stdio.h>
#include <iostream>
#include "NoeudListe.h"
template <class T> class Liste
{
private:
NoeudListe<T>* tete;
NoeudListe<T>* fin;
public:
Liste()
{
tete = new NoeudListe<T>(NULL,fin,NULL); //<-----I think the problem lies here beacause the val can`t be NULL? But I tried 0, still not work...
fin = new NoeudListe<T>(tete,NULL,NULL);
}
void insert_after (T& val, NoeudListe<T>* location)
{
NoeudListe<T>* local = new NoeudListe<T>(location,location->getNext(),val);
(*(location->getNext())).setPrev(local);
location->setNext(local);
}
void insert_first(T& val)
{
insert_after (val, tete);
}
void insert_last(T& val)
{
insert_after (val, fin->getPrev());
}
friend std::ostream& operator << (std::ostream& os,const Liste<T>& location)
{
NoeudListe<T>* local=(location.tete)->getNext();
while( local->getVal() != NULL )
{
os<< local->getVal() << "\n";
local=local->getNext();
}
return os;
}
};
-----NoeudListe.h------
#pragma once
template <class T> class NoeudListe
{
private:
NoeudListe* prev;
NoeudListe* next;
T val;
public:
NoeudListe(NoeudListe* p, NoeudListe* n, const T& v)
{
prev = p;
next = n;
val = v;
}
void setNext(NoeudListe* n){ next = n;}
void setPrev(NoeudListe* p){ prev = p;}
void setVal(const T& v){ val = v;}
NoeudListe* getNext(){ return next;}
NoeudListe* getPrev(){ return prev;}
T getVal(){ return val;}
};
答案 0 :(得分:0)
friend std::ostream& operator << (std::ostream& os,const Liste<T>& location)
{
NoeudListe<T>* local=(location.tete)->getNext();
while( local->getVal() != NULL )
{
os<< local->getVal() << "\n";
local=local->getNext();
}
return os;
}
如果local
为NULL(如果local->getVal()
为NULL,为什么要测试?),这里不测试,所以你会在这里得到一个段错误。