调用函数只有在函数开头有cout语句时才会给出结果

Calling a function gives result only if it has a cout statement in the beginning

本文关键字:函数 结果 cout 开头 调用 语句      更新时间:2023-10-16

我试图在c++中实现一个简单的堆栈。除了这个函数minm()之外,我的代码工作得很好。我得到了意想不到的结果。如果我注释掉粗体的行,那么我的过程甚至不会运行。此外,您可以看到我的函数minm() &Minmm()属于粗体行。请帮帮我。

解释如下:

Functions minm() & &cout<<"called"<<

#include<iostream>
using namespace std;
const int MAX_ALLOWED_SIZE = 100000000;
class MyStack{
    int *a;
    int *min, *max;
    int top;
    int size;
    public:
        MyStack(int s=MAX_ALLOWED_SIZE);
        void push(int i);
        int pop();
        int maxm();
        int minm()  // This function is failing
        {
            //cout<<"calledt";
            if(!stackEmpty())
            {
                cout<<min[top]<<" = " <<a[min[top]]<<endl;
                return a[min[top]];
            }
            return NULL;
        }
        int minmm()   // This function is working
        {
            cout<<"calledt";
            if(!stackEmpty())
            {
                cout<<min[top]<<" = " <<a[min[top]]<<endl;
                return a[min[top]];
            }
            return NULL;
        }
        bool stackEmpty();
        void printStack();
};
int main()
{
    MyStack s;
    int t;
    while(true)
    {
        scanf("%d",&t);
        s.push(t);
        cout<<"min = "<<s.minm()<<endl;
        cout<<"min = "<<s.minmm()<<endl;
        if(t==-1) break;
    }
}
输入:

234
23
-1
输出:

min = 0
called  a[0] = 234
min = 234
min = 0
called  a[1] = 23
min = 23
min = 0
called  a[2] = -1
min = -1

现在,我从ideone上的两个函数得到相同(错误)的结果,而函数minmm()在我的系统上返回(我在Code::Blocks 12.11中使用GNU GCC编译器)。

在你的stackEmpty中,你没有返回false:

bool stackEmpty(){
    if(top == -1) return true;
    return false;
}

bool stackEmpty(){
    return (top == -1);
}