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

#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;

}


慕粉13247635475
浏览 1425回答 2
2回答

下雨何

sorry,不懂c不过大体上了解一点点,要注意变量的声明和销毁,另外注意变量类型c不比php,它是强数据类型,不能简单随意的转换数据类型c不比java,它对内存的控制比较严格,不像java,都叫给虚拟机,不用管这些,同时java也不用考虑指针建议多了解一点 指针,数据在内存的存放等等

onemoo

在构造函数中,你想申请一块连续size个char内存,是不是?pStack = new char(Size);不过上面这代码写错了,申请一块连续内存需要在类型后用中括号 [ ]。 你写成了小括号,这样只是申请了一个char内存,其初值为size而已。
打开App,查看更多内容
随时随地看视频慕课网APP