【发布时间】:2017-09-11 21:03:13
【问题描述】:
每次我运行它都会给我这个错误分段错误;核心转储; 我试图在 C++ 中做一个linkedStack。 我的代码是:
节点.h
class Node {
public:
Node(int element);
const int& getElement()const;
Node *getNext() const;
void setNext(Node *e);
Node(const Node& orig);
virtual ~Node();
private:
int element;
Node *next;
};
节点.cpp
#include "Node.h"
Node::Node(int element) {
this->element=element;
}
const int& Node::getElement() const{
return element;
}
Node * Node::getNext() const{
return next;
}
void Node::setNext(Node *e){
next=e;
}
Node::Node(const Node& orig) {
}
Node::~Node() {
}
LinkedStack.h
#include "Node.h"
#include <iostream>
#include "EmptyException.h"
class LinkedStack {
public:
LinkedStack();
int size() const;
const Node& top() const;
void push(const int& element);
void pop();
void print();
LinkedStack(const LinkedStack& orig);
virtual ~LinkedStack();
private:
Node *front=NULL;
int num_elements;
};
LinkedStack.cpp
#include "LinkedStack.h"
using namespace std;
LinkedStack::LinkedStack() {
}
int LinkedStack::size() const{
return num_elements;
}
const Node& LinkedStack::top() const{
return *front;
}
void LinkedStack::push(const int& element){
Node *newfront=new Node(element);
newfront->setNext(front);
front=newfront;
delete newfront;
num_elements++;
}
void LinkedStack::pop(){
if(num_elements==0){
throw EmptyException();
}
else{
Node *oldfront=front;
front=front->getNext();
num_elements--;
}
}
void LinkedStack::print(){
Node *temp=front;
while(temp != __null){
cout<<temp->getElement()<<endl;
temp=temp->getNext();
}
cout<<""<<endl;
}
LinkedStack::LinkedStack(const LinkedStack& orig) {
}
LinkedStack::~LinkedStack() {
}
main.cpp
#include <cstdlib>
#include <iostream>
#include <string>
#include "LinkedStack.h"
using namespace std;
/*
*
*/
int main(int argc, char** argv) {
string menu[]={"1.Afegir","2.Eliminar","3.Mostrar","4.Sortir"};
int opc,element;
LinkedStack Stack;
do{
for(int i=0;i<4;i++){
cout<<menu[i]<<endl;
}
cout<<"Selecciona una opció"; cin>>opc; cout<<""<<endl;
switch(opc){
case 1:
cout<<"Que vols afegir?... "; cin>>element; cout<<""<<endl;
Stack.push(element);
break;
case 2:
cout<<"Eliminant.... "<<endl;
Stack.pop();
break;
case 3:
Stack.print();
break;
}
}while(opc!=4);
return 0;
}
就是这样。 当我尝试第一个选项(推送)时没有问题,但是当我尝试弹出或打印堆栈时,它给了我核心转储:分段错误错误。
我认为问题在于指针(??),但我仍然不知道在哪里或如何。
如果你能帮上忙就好了^^
【问题讨论】:
-
__null- 那是什么? -
请edit您的问题提供minimal reproducible example。
-
Node::Node(int)离开next未初始化。
标签: c++ pointers memory segmentation-fault stack