求问为什么我的程序会奔溃

来源:-

慕粉13247635475

2016-09-11 16:06

#include<iostream>

using namespace std;

class MyStack {

public:

MyStack(int Size);

~MyStack();

bool stackEmpty();

bool stackFull();

void clearStack();

int stackLength();

//char push(char elem);

bool push(char elem);

bool pop(char &elem);

void stackTravel();

private:

int size;

int top;

char *pStack;


};

 

MyStack::MyStack(int Size)

size=0;

top=0;

size = Size;

pStack = new char(Size);

cout<<"申请"<<size<<"个内存的空间!"<<endl;

}


MyStack::~MyStack()

{

delete []pStack;

pStack=NULL;

cout<<"delete"<<endl;

}


bool MyStack::stackEmpty()

{

if (top==0)

return true;

else

return false;

}


bool MyStack::stackFull()

{

if(size==top)

return true;

else

return false;

}


void MyStack::clearStack()

{

top = 0;//覆盖

}


int MyStack::stackLength()

{

return  top;

}


bool MyStack::push(char elem)

{

if(stackFull()){

return false;

}

pStack[top]=elem;

top++;

return true;

}

bool MyStack::pop(char &elem){

    if(!stackEmpty())

    {

        top--;

        elem=pStack[top];

         

        return true;

    }

    else

    {

        return false;

    }

}

void MyStack::stackTravel()

{

for (int i = 0;i < top;i++) {

cout << pStack[i];

}

cout << endl;

}




int main() {

MyStack pStack(5);

char elem;

char num[5]={'1','2','3','4','5'};

for(int i=0;i<5;i++){

pStack.push(num[i]);

}

//pStack.push('p');

//pStack.push('p');

pStack.pop(elem);

if (pStack.stackEmpty()) {

cout << "The stack is empty"<<endl;

}

if (pStack.stackFull()) {

cout << "The stack is full" << endl;

}

cout << "The stack's length:" << pStack.stackLength() << endl;

/*pStack.push('a');

pStack.push('p');

pStack.push('p');

pStack.push('l');*/

//pStack.push('e');

//pStack.stackTravel();

/*pStack.pop(elem);

cout << elem << endl;

pStack.clearStack();*/

//cout << "The stack's length:" << pStack.stackLength() << endl;

return 0;

}


写回答 关注

1回答

  • 晚唱
    2017-06-14 15:28:40

    构造函数里,申请内存应该是new char[Size]吧。

数据结构探险—栈篇

栈,先入后出(FILO),带领大家体会栈这种数据结构的美妙

62724 学习 · 102 问题

查看课程

相似问题