切糕战士:求一C++程序,要用上类和对象,构造函数,析构函数,继承与派生的知识编一个程序,谢谢!

来源:百度文库 编辑:高考问答 时间:2024/04/30 04:38:11
编一或两个程序,如果只一个程序,必须用上以上的知识,内容不限,谢谢!
要有注释说明,并写上程序的功能和作用

#include <iostream>
using namespace std;

//线性表的抽象类

template <class T>
class LinerList
{
private:
T * data; //线性表以数组形式存放
int MaxSize; //表空间最大范围
int Last; //当前存入的数据单元个数,即表长
public:
LinerList (int MaxSize=10); //构造函数
~LinerList (void); //析构函数
bool IsEmpty (void); //判断表是否为空
bool IsFull (void); //判断表是否已满
virtual int write (T x)=0; //在表中写入数据
virtual T read(void)=0; //读出数据
virtual int count(void); //计算当前存入的数据单元个数
T Deletehead(void); //删除表中的头结点并返回被删除结点的数据
T DeleteTail(void); //删除表中的尾结点并返回被删除结点的数据
int AddTail(const T xdata); //在表的尾部增加结点

};

template <class T>
LinerList <T>::LinerList(int sz)
{
if (sz>0)
{
MaxSize=sz;
Last=0;
data=new T [MaxSize];
}
}

template<class T>
LinerList <T>::~LinerList(void)
{
delete[]data;
}

template<class T>
bool LinerList <T>::IsEmpty(void)
{
return(Last<=0)?true:false;
}

template <class T>
bool LinerList <T>::IsFull (void)
{
return (Last>=MaxSize)?true:false;
}

template<class T>
int LinerList <T>::count (void)
{
return Last;
}

template<class T>
int LinerList <T>::AddTail(const T xdata)
{
//写入数据。若表不满,则写入x,返回0;否则返回-1
if (!IsFull())
{
data[Last++]=xdata;
return 0;
}
else return -1;
}

template<class T>
T LinerList <T>::DeleteTail(void)
{
//删除表中的尾结点.若表非空,则删除表中的尾结点;否则返回NULL
if (!IsEmpty()) return data[--Last];
else return NULL;
}

template<class T>
T LinerList <T>::Deletehead(void)
{
//删除表中的头结点.若表非空,则删除表中的头结点;否则返回NULL
if (!IsEmpty())
{
T te;
te=data[0];
for (int i=1;i<Last;i++)
{
data[i-1]=data[i];
}
Last--;
return te;
}
else return NULL;
}

//堆栈类
template<class T>
class Stack : public LinerList<T>
{
public:
int write (T x) //在堆栈中写入数据(入栈)
{
return AddTail(x);
}
T read(void) //读出栈的数据(出栈)
{
return DeleteTail();
}
};

//队列类
template<class T>
class Queue : public LinerList<T>
{
public:
int write (T x) //在队列中写入数据(入队)
{
return AddTail(x);
}
T read(void) //读出队列的数据(出队)
{
return Deletehead();
}

};

template<class T>
T read (LinerList<T> & node)
{
return node.read();
}

int _tmain(int argc, _TCHAR* argv[])
{
Stack<int> stack;
Queue<char *> queue;

queue.write("abc");
queue.write("def");
stack.write(2);
stack.write(3);
stack.write(4);
cout<<stack.count()<<endl;
cout<<queue.count()<<endl;
cout<<read(stack)<<endl;
cout<<stack.count()<<endl;
cout<<read(queue)<<endl;
cout<<queue.count()<<endl;

cin>>argc;

return 0;
}