1

我只是在用 C++ 开发一个简单的堆栈程序。

#include<iostream>
#define MAX 3;
using namespace std;

class stack
{
private:
    int arr[3];
    int top;

public:
    stack()
    {
        top=-1;
    }
    void push(int item)
    {
        if(top==MAX-1)
        {
            cout<<endl<<"STACK FULL";
            return;
        }
        top++;
        arr[top]=item;
        cout<<endl<<"Pushed "<<item;
    }
    int pop()
    {
        if(top==-1)
        {
            cout<<endl<<"STACK EMPTY";
            return NULL;
        }
        int temp=arr[top];
        top--;
        return temp;
    }
};

int main()
{
    stack s;
    s.push(1);
    s.push(2);
    s.push(3);
    s.push(4);

    cout<<endl<<"Popped "<<s.pop();
    cout<<endl<<"Popped "<<s.pop();
    cout<<endl<<"Popped "<<s.pop();
    cout<<endl<<"Popped "<<s.pop();
}

我得到了这个作为礼物

naveen@linuxmint ~/Desktop/C++ $ g++ stack.cpp -o stack
stack.cpp: In member function ‘void stack::push(int)’:
stack.cpp:18:11: error: expected ‘)’ before ‘;’ token
stack.cpp:18:16: error: expected ‘;’ before ‘)’ token
stack.cpp: In member function ‘int stack::pop()’:
stack.cpp:32:11: warning: converting to non-pointer type ‘int’ from NULL [-Wconversion-null]

当我删除# define MAX 3并且return NULL没有错误时。为什么会出现错误?

4

2 回答 2

19

;从您的define MAX 3 ;线路中删除。这将扩展到类似

if(top==3 ;-1)

这绝对不是你想要的。请记住,这#define是一个预处理器指令,而不是 C 语句。

一个可能更好的主意是将其更改为常量而不是#define使用类似的东西

static const unsigned MAX = 3;

这完全避免了所有的预处理器。

于 2013-08-12T14:54:52.767 回答
12

在 中定义常量不是一个好主意#define

更改#define MAX 3;#define MAX 3

与此相关的文章:-不要用分号结束宏定义

一种替代方法可能是:-

static const unsigned MAX = 3;
于 2013-08-12T14:54:53.520 回答