【问题标题】:Error in C++ due to # define MAX [duplicate]由于#define MAX而导致C ++出错[重复]
【发布时间】:2013-08-12 14:53:54
【问题描述】:

我只是在用 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 3return NULL 时,我没有收到任何错误。为什么会出现错误?

【问题讨论】:

  • 这是 C++,您可能希望将 #define MAX 3; 替换为 static const int MAX = 3;
  • 很容易与MAX 之类的宏名称发生冲突。我建议使用 static const size_t MaxStackSize = 3; 之类的东西完全避免使用宏。
  • 其次,为什么我会因为NULL而收到警告?
  • @Insane,那是因为你从一个应该返回 int 的方法返回 NULL

标签: c++


【解决方案1】:

从您的define MAX 3 ; 行中删除;。这将扩展为类似

if(top==3 ;-1)

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

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

static const unsigned MAX = 3;

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

【讨论】:

  • +1 提供替代方案。
【解决方案2】:

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

#define MAX 3; 更改为#define MAX 3

与此相关的文章:- Do not conclude macro definitions with a semicolon

替代方案可能是:-

static const unsigned MAX = 3;

【讨论】:

  • 对常量使用#define 是个坏主意,因为它忽略了作用域
  • 还有type safety
  • @UchiaItachi:- 是的,我同意!!! :)
猜你喜欢
  • 2022-11-23
  • 1970-01-01
  • 2018-04-23
  • 2020-01-17
  • 1970-01-01
  • 2021-05-15
  • 1970-01-01
  • 1970-01-01
  • 2013-03-13
相关资源
最近更新 更多