首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

产生段错误

2012-09-08 
产生段异常#include iostreamusing namespace stdtemplate class Tclass LinearList{public:virtual

产生段异常
#include <iostream>
using namespace std;

template <class T> 
class LinearList 

  public:  
  virtual bool IsEmpty() const=0; 
  virtual int Length() const=0;  
  virtual bool Find(int i,T& x) const=0;  
  virtual int Search(T x) const=0;  
  virtual bool Insert(int i,T x)=0;
  virtual bool Delete(int i)=0;  
  virtual bool Update(int i,T x)=0;
  virtual void shuchu()const=0; 
  protected:
  int n; //线性表的长度
};
 
 
template <class T>
class SeqList:public LinearList<T>

public:
SeqList(int mSize);
~SeqList() { delete [] elements;};
bool IsEmpty() const;
int Length() const;
bool Find(int i,T& x) const;  
int Search(T x) const; 
bool Insert(int i,T x);
bool Delete(int i);
bool Update(int i,T x);
void shuchu()const ; 
private:
  int n;
int maxLength; //顺序表的最大长度
T *elements; //动态一维数组的指针
};
template <class T>
SeqList<T>::SeqList(int mSize)

maxLength=mSize;
elements=new T[maxLength]; //动态分配顺序表的存储空间
int n=0;
}
template <class T>
bool SeqList<T>::IsEmpty() const

return n==0;
}
template <class T>
int SeqList<T>::Length() const

return n;
}
template<class T>
bool SeqList<T>::Find(int i,T& x) const

if (i<0 || i>n-1){ //对i进行越界检查
cout<<"Out of Bounds"<<endl; return false;
}
x=elements[i]; //通过引用参数x返回下标为i的元素
return true;
}
template<class T>
int SeqList<T>::Search(T x) const

for(int j=0;j<n;j++)
if (elements[j]==x) return j; //从头开始搜索值为x的元素
return -1;
}
template<class T>
bool SeqList<T>::Insert(int i,T x)
{  
if (i<-1 || i>n-1) { 
cout<<"Out Of Bounds"<<endl; return false;
}
if (n== maxLength){ //上溢出检查
cout<<"OverFlow"<<endl; return false;
}
for (int j=n-1;j>i;j--) elements[j+1]=elements[j]; //从后往前逐个后移元素
elements[i+1]=x; //将x插入下标为i的元素后面
n++; return true;
}
template <class T>
bool SeqList<T>::Delete(int i)

if (!n) { //下溢出检查
cout<<"UnderFlow"<<endl; return false;
}
if (i<0 || i>n-1) {
cout<<"Out Of Bounds"<<endl; return false;
}
for (int j=i+1;j<n;j++) elements[j-1]=elements[j]; //从前往后逐个前移元素
n--; return true;
}
template <class T>
bool SeqList<T>::Update(int i,T x)

if (i<0 || i>n-1) { 
cout<<"Out Of Bounds"<<endl; return false;
}
elements[i]=x; //将下标为i的元素值修改为x
return true;
}
template <class T>
void SeqList<T>::shuchu()const
{
for (int i=0; i<n; i++) cout<<elements[i]<<" ";
cout<<endl;
}



int main()
{
  int n;
  SeqList<int> L(20);
  for(int i=0;i<5;i++)
  {
  L.Insert(i-1,i);
   
  }
 L.shuchu();
system("pause");
return 0;
}

[解决办法]
SeqList<T>::SeqList(int mSize)
{
maxLength=mSize;
elements=new T[maxLength]; //动态分配顺序表的存储空间
n=0;//改 int n=0;
}

[解决办法]
楼主,你的LinearList内定义了n表示长度,为什么SeqList继承后又不用呢??

C/C++ code
SeqList<T>::SeqList(int mSize){   maxLength=mSize;elements=new T[maxLength]; //动态分配顺序表的存储空间n=0;//改 int n=0;} 

热点排行