0

我正在我目前的 CS 课程中学习堆栈。我正在处理函数,当我去测试时,对于 pop 函数,我得到了错误:“没有匹配函数调用 DynStack::pop()”

这是我的代码:

主要的()

#include <iostream>
#include <cstddef>
#include "src\DynStack.cpp"
#include "DynStack.h"

using namespace std;


int main()
{
    DynStack<char>cstack;
    cstack.push('A');
    cstack.push('B');
    cstack.push('C');

    cstack.pop();

    cout << cstack.top->value << endl;

    return 0;
}

动态堆栈.cpp

#include "DynStack.h"
#include <cstddef>

template<typename T>
DynStack<T>::DynStack()
{
    top = NULL;
}

template<typename T>
void DynStack<T>::push(T val)
{
    StackNode *nodePtr; // ptr to traverse thru the stack

    StackNode *newNode;
    newNode = new StackNode; // makes a new StackNode
    newNode->value = val;
    newNode->next = NULL;

    if (top == NULL) // If the stack is empty
    {
        top = newNode; // Make newNode the first node;
    }
    else
    {
        nodePtr = top; // make our ptr = top

        nodePtr->next = newNode; // make the node after the top our newNode

        top = newNode; // newNode is our new top of the stack
    }
}

template <typename T>
void DynStack<T>::pop(T &)
{
    StackNode *nodePtr; // makes a nodePtr to traverse the stack

    if (top == NULL)
    {
        return;
    }
    else
    {
        nodePtr = top;
        nodePtr = top--;
        delete top;
        top = nodePtr;
        delete nodePtr;
    }

}




template <typename T>
DynStack<T>::~DynStack()
{
    //dtor
}

动态堆栈.h

#ifndef DYNSTACK_H
#define DYNSTACK_H

template <typename T>
class DynStack
{
    private:
        struct StackNode
        {
            T value;
            StackNode *next;
        };

        StackNode *top;

    public:
        DynStack();
        ~DynStack();
        void push(T);
        void pop(T&);
        bool isEmpty();
};

#endif // DYNSTACK_H

我还处于测试这个程序的早期阶段。我假设我必须在 cstack.pop(); 的括号中放一些东西,但我不知道我会放什么?Pop 只会删除一个值,是吗?我认为它不需要任何输入。

如果这是我的程序,我会考虑从 void DynStack::pop(T &) 中删除 T&,但这是我的教授放在那里的。我想他把那个放在那里,所以我必须学习这个。谷歌搜索了一堆,但没有靠近。

谢谢大家。

4

1 回答 1

0

在您的代码中

void pop(T&);

T& 意味着这个函数需要一个类型的(参考)参数Tchar在你的情况下)。您没有提供一个,因此代码无法编译。您需要在代码中添加一个 char 变量

char x;
cstack.pop(x);
cout << "the top item on the stack was " << x << endl;

我认为您缺少的是pop不仅从堆栈中删除一个项目,它还通过引用参数“返回”该项目。

于 2020-04-28T04:08:53.350 回答