为了账号安全,请及时绑定邮箱和手机立即绑定

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

#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 回答

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

1 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消

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

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信