C++,类模版相关的问题求大神 写了一个简单的栈

2025-05-13 17:15:53
推荐回答(1个)
回答1:

这个要细心啊。很多问题都是不细心导致的。你main函数里面没写所以我只改了你错的地方,请看代码后的注释。

#include
using namespace std;
template
class Stack
{
public:
    explicit Stack(int capacity = 10);
    bool IsEmpty()const;
    bool IsFull()const;
    void MakeEmpty(){ top = -1; }
    void Pop();
    void Push(const Object&);
    Object TopAndPop();
    const Object&Top() const;
    ~Stack()
    {
        if (theArray)
        {
            delete[]theArray;
        }
        theArray = NULL;
    }
private:
    int MaxSize;
    int top;
    Object*theArray;
};

template
 Stack::Stack(int capacity)//和你的构造函数要匹配
{
    MaxSize = capacity;
    theArray = new Object[capacity];
    top = -1;
}
template
bool Stack::IsEmpty()const//要和申明匹配啊 const类型
{
    return top == -1;
}
template
bool Stack::IsFull()const//要和申明匹配啊 const类型
{
    return top == MaxSize - 1;
    
}
template
void Stack::Push(const Object&x)
{
    if (!IsFull())
    {
        theArray[++top] = x;
    }  
}
template
void Stack::Pop()
{
    if (!IsEmpty())
    {
        --top;
    }
    else
    {   
        cout << "栈空了" << endl;
        return;
    }
}
template
const Object & Stack::Top()const//你这里类名写错了(Satck 改成Stack)看了好久- -才发现
{
    if (!IsEmpty())
    {
        return theArray[top];
    }
    else
    {
        cout << "客栈空了" << endl;
        return -1;
    }
}
template
Object Stack::TopAndPop()
{
    if (!IsEmpty())
    {
        return theArray[top--];
    }
}
int main()
{
    return 0;
}