关于栈编译无错,运行有错!
栈头文件stack.h
template <class ElemType>class SqStack{public: SqStack(int size = 0); //构造函数 virtual ~SqStack();//析构函数 int Length() const;//求栈长度 bool EmptyStack() const; //判断栈是否为空 void Clear();//清空栈 void Trasearse() const;//遍历栈 void Push(const ElemType &elem);//入栈 void Pop(ElemType &elem);//出栈 void PopTop(ElemType &elem) const;//返回栈顶元素 SqStack(const SqStack<ElemType> ©);//复制构造函数 SqStack<ElemType> &operator = (const SqStack<ElemType> ©);//赋值运算符重载protected: ElemType *data; int count; int MaxSize; void Init(int size); bool Full() const;};
#include "Stack.h"#include <iostream>using namespace std;template <class ElemType>bool SqStack<ElemType>::Full() const{ return count == MaxSize;}template <class ElemType>void SqStack<ElemType>::Init(int size){ MaxSize = size; if (data) { delete []data; } data = new ElemType[MaxSize]; count = 0;}template <class ElemType>SqStack<ElemType>::~SqStack(){ delete []data;}template <class ElemType>int SqStack<ElemType>::Length() const{ return count;}template <class ElemType>bool SqStack<ElemType>::EmptyStack() const{ return count == 0;}template <class ElemType>void SqStack<ElemType>::Clear()//将栈清空{ count = 0;}template <class ElemType>void SqStack<ElemType>::Push(const ElemType &elem){ if (!Full()) { data[count++] = elem; }}template <class ElemType>void SqStack<ElemType>::Pop(ElemType &elem) { if (!EmptyStack()) { elem = data[count--]; }// else// cerr<<"Stack Pop erre!"<<endl;}template <class ElemType>void SqStack<ElemType>::PopTop(ElemType &elem) const{ if (!EmptyStack()) { elem = data[count]; }// else// cerr<<"Stack PopTop()err!"<<endl;}template <class ElemType>SqStack<ElemType>::SqStack(const SqStack<ElemType> ©){ data = NULL; Init(copy.MaxSize); count = copy.count; for (int cur = 0; cur < Length(); cur++) { data[cur] = copy.data[cur]; }}template <class ElemType>SqStack<ElemType>&SqStack<ElemType>::operator =(const SqStack<ElemType> ©){ if (© != this) { Init(copy.MaxSize); count = copy.count; for (int cur = 0; cur < Length(); cur++) { data[cur] = copy.data[cur]; } } return *this;}
#include "stack.h"#include <iostream>using namespace std;int main(){ SqStack<int>ss(10); SqStack<int>tempSS; int e; ss.Push(20); ss.Push(10); ss.Push(1); tempSS = ss; ss.Pop(e); cout << e <<endl; return 0;}
elem = data[--count];
同理,取栈顶元素函数里也应该修改相应的一行为
elem = data[count-1];
此外,你的构造函数SqStack(int size = 0)和成员函数 void Trasearse() const只有申明没有定义。