-1

这就是我想出的,我只想让程序弹出堆栈中的前 2 个值,计算它们并将其推回堆栈......我已经创建了所需的函数,但似乎有问题将两个数字相加的函数。

#include <iostream>   

using namespace std;
int Maxlenght=5;
class stackhouse{
private:
    int *CreateArray;
    int top;
public:
    stackhouse();
    bool IsEmpty();
    bool IsFull();
    void constructor();
    void Push(int);
    void Pop(int);
    void Sum();
    void Sub();
};
stackhouse::stackhouse(){
    CreateArray= new int[Maxlenght];
    top=-1;
}
bool stackhouse::IsEmpty()
{
    if (top==-1) return 1;
    else return 0;
}
bool stackhouse::IsFull(){
    if (top==Maxlenght-1) return 1;
    else return 0;
}
void stackhouse::Push(int number){
    top++;
    CreateArray[top]=number;
}
void stackhouse::Pop (int number){
    number=CreateArray[top];
    top--;
}
void stackhouse::Sum(){
    int number=7,sum=5;
    Pop(sum);
    Pop(number);
    sum+=number;
    Push(sum);
    cout<<sum;
}
void main(){
    int number;
    stackhouse stack1;
    stackhouse();
    cout<<"Please fill the stack...";
    stack1.Push(5);
    stack1.Push(2);
    cout<<"The sum is...";
    stack1.Sum();
}
4

2 回答 2

3

Pop函数需要返回number或通过number引用传递;否则,赋值number无效。

void stackhouse::Pop(int& number) {  // <-- add the &
    number = CreateArray[top];
    top--;
}

或者

int stackhouse::Pop() {
    int number = CreateArray[top];
    top--;
    return number;
}

(请注意,第二种方式需要您编写sum = Pop()而不是Pop(sum).)

于 2013-06-02T04:09:24.617 回答
1

将参数按值传递给 pop() 方法是没有意义的。它需要返回一个值。

于 2013-06-02T04:08:51.900 回答