模板实现分段错误;

Template implementation segmentation error;

本文关键字:错误 分段 实现      更新时间:2023-10-16

在我为代码引入模板之前,一切都在工作编辑:感谢您的提示,这是我能够缩小范围的问题:

在 main.cpp:4 中包含的文件中:stack.cpp:在成员函数中void Stack<TYPE>::push(Stack<TYPE>&, TYPE)': stack.cpp:35: error:节点'不是一种类型

我想知道类似的问题是否会在 pop 函数中出现,但似乎没有。

我很困惑为什么它似乎坚持节点不是一种类型。

编辑#2:main.cpp 文件中的此语句现在会导致麻烦。我已经将所有定义从堆栈中移出.cpp移动到stack.h。在此之后Stack<int> list;我的编译说Segmentation fault (core dumped).

堆栈.h:

#include <iostream>
using namespace std;
template <typename TYPE>
struct node {
    TYPE data;
    node<Type> *next;
    node(){
        data = NULL;
        next = NULL;
    }
    ~node(){
        if (data!=0)
            delete next;
    }
    explicit node(int i){
        data = i;
    }
};
template <typename TYPE>
class Stack {
private:
    node<TYPE> *top;
    void init();
public:
    Stack(); // default constructor
    virtual ~Stack(); // destructor
    bool empty();
    void push(Stack&,TYPE);
    TYPE pop(Stack&);
    int peek();
    void clear();
    ostream& printf(ostream&, node<TYPE> *);
    ostream& print(ostream&);
    ostream& sequentialPrint(Stack&,ostream&);
    ostream& reversePrint(Stack&,ostream&);
    friend ostream& operator<<(ostream&, Stack&);
};

堆栈.cpp:

template <typename TYPE>
void Stack<TYPE>::push(Stack<TYPE> &s, TYPE i) {
    node<TYPE> * n = new node(i);
    n->next = top;
    top = n;
}
template <typename TYPE>
TYPE Stack<TYPE>::pop(Stack<TYPE> &s){
    if (empty()) {
        cerr<<"Stack is empty n";
    }
    TYPE temp = s.top->data;
    top = top->next;
    return temp;
}
  1. 不需要friend ostream& operator<<(ostream&, Stack&);
  2. 不能cpp文件中定义模板方法。模板参数依赖的每个元素都必须在头文件中定义。