【发布时间】: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 3 和 return NULL 时,我没有收到任何错误。为什么会出现错误?
【问题讨论】:
-
这是 C++,您可能希望将
#define MAX 3;替换为static const int MAX = 3;。 -
很容易与
MAX之类的宏名称发生冲突。我建议使用static const size_t MaxStackSize = 3;之类的东西完全避免使用宏。 -
其次,为什么我会因为NULL而收到警告?
-
@Insane,那是因为你从一个应该返回
int的方法返回NULL。
标签: c++