读书人

栈有关问题

发布时间: 2012-08-09 15:59:21 作者: rapoo

栈问题!
栈头文件stack.h

C/C++ code
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> &copy);//复制构造函数    SqStack<ElemType> &operator = (const SqStack<ElemType> &copy);//赋值运算符重载protected:    ElemType *data;    int count;    int MaxSize;    void Init(int size);    bool Full() const;};


栈实现文件Stack.cpp
C/C++ code
#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> &copy){    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> &copy){    if (&copy != this)    {        Init(copy.MaxSize);        count = copy.count;        for (int cur = 0; cur < Length(); cur++)        {            data[cur] = copy.data[cur];        }    }    return *this;}


栈测试文件main.cpp
C/C++ code
#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;}


编译没错,但是运行有错!
错误1error LNK2019: 无法解析的外部符号 "public: virtual __thiscall SqStack<int>::~SqStack<int>(void)" (??1?$SqStack@H@@UAE@XZ),该符号在函数 _main 中被引用E:\C\Win32\栈\栈\main.obj栈
.
.
.
错误6error LNK1120: 5 个无法解析的外部命令E:\C\Win32\栈\Debug\栈.exe11栈

请指教下!

[解决办法]
模版实现也要放头文件里
[解决办法]
楼主把你的头文件和cpp文件合并在一起吧。模板不支持这样的。必须写在一个文件里。

读书人网 >C++

热点推荐