模板实现分段错误;
Template implementation segmentation error;
在我为代码引入模板之前,一切都在工作编辑:感谢您的提示,这是我能够缩小范围的问题:
在 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;
}
- 不需要
friend ostream& operator<<(ostream&, Stack&);
- 不能
cpp
文件中定义模板方法。模板参数依赖的每个元素都必须在头文件中定义。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 为什么我使用 std::copy() 收到运行时错误(分段错误)?
- 为什么我的代码包含错误分段错误(核心转储)?
- 为什么会出现此错误?- 分段错误(核心转储)
- 意外的运行时错误(分段错误)
- C++将文本文件读入数组,运行错误:分段错误
- mmap 错误:分段错误/指针无效错误
- 在我的代码中找不到错误....分段错误
- 错误:分段故障(核心转储)阵列
- 用string.h将错误分段到队列中
- c++字符串流转换错误:分段错误
- 为什么我的代码显示错误分段错误(核心转储)