我有两个代码,一个.cpp和一个.h,我想使用两种方法创建一个堆栈,POP和PUSH通过从cpp调用它们
错误:PUSH(int val)不能重载(与POP()相同)
# include < iostream >
# include " LibStack.h "
using namespace std;
using namespace STACK;
int main()
{
Stack S1;
int elm;
cout << "Insert value:"<< endl;
cin >> elm;
S1.PUSH(elm);
S1.POP();
return 0;
}
# ifndef _LibStack_H_
# define _LibStack_H_
# define MAX_STACK 10
using namespace std;
namespace STACK
{
class Stack
{
private:
int stack[MAX_STACK];
int MIN_STACK = 0;
public:
void PUSH(int);
void POP();
PUSH(int val)
{
if(MIN_STACK < MAX_STACK)
{
stack[MAX_STACK+1] = val;
}
else
cout << "Full stack!" << endl;
}
POP()
{
int aux;
if(MIN_STACK >= 0)
{
aux = stack--[MIN_STACK];
cout << " POP " << endl << aux << endl;
}
else
cout << "Empty stack!" << endl;
}
};
}
# endif // __LibStack_H_
答案 0 :(得分:0)
下面几个随机点,没有假装成一个完整的清单。
select now();
class Stack // template <class Stack>
// void PUSH(int);
// void POP();
void PUSH(int val) // PUSH(int val)
stack[MIN_STACK++] = val; // MIN_STACK += 1; stack[MAX_STACK] = val;
void POP() // POP()
// if(MIN_STACK >= 0) { MIN_STACK -= 1; aux = stack[MIN_STACK+1];
答案 1 :(得分:0)
您可以像这样定义一个类:
class Stack
{
private:
int stack[MAX_STACK];
int MIN_STACK = 0;
public:
. . .
}
推送功能可以按如下方式实现:
在插入之前增加MIN_STACK的值时,总是将stack [0]留空并浪费空间。同时使用MIN_STACK
作为索引而不是MAX_STACK
,因为MAX_STACK
的值始终为10。
void PUSH(int val)
{
if(MIN_STACK < MAX_STACK)
{
stack[MIN_STACK++] = val;
/*
Here MIN_STACK is incremented after insertion. It is the same as stack[MIN_STACK] = val;
MIN_STACK +=1;
*/
}
else
cout << "Full stack!" << endl;
}
在POP功能中,如果MIN_STACK
为0,则无需删除任何内容,因为每次推送值MIN_STACK
都会增加。MIN_STACK
始终指向下一个空闲位置。因此,要弹出的数据位于(MIN_STACK-1)
位置。因此递减MIN_PATH
并使用它。
void POP()
{
int aux;
if(MIN_STACK > 0)
{
aux = stack[--MIN_STACK];
/* Here MIN_STACK is decremented before popping out. It is the same as MIN_STACK -= 1;
aux = stack[MIN_STACK]; */
cout << " POP : " << aux << endl;
}
else
cout << "Empty stack!" << endl;
}
在您的cpp
文件中,创建类的对象:
Stack S1;
S1.PUSH(elm);
S1.POP();