需要一些类和头文件的建议

问题描述:

我在做什么?

我有两个代码,一个.cpp和.H,我想从CPP美其名曰需要一些类和头文件的建议

输出错误创建使用2种方法,POP和PUSH堆栈(更新)

错误:PUSH(INT VAL)不能被重载(同样与POP())

编译克++ -Wall -O2 Stack.cpp -o堆栈

CPP的代码

# 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_ 
+4

'模板'这是不是类的声明方式。 – tkausl

+0

现在我有更多疑惑了,你如何使用模板声明一个类? “ – Bit89

+1

”Stack S1“

你可以这样定义一个类:

class Stack 
{ 

private: 

    int stack[MAX_STACK]; 
    int MIN_STACK = 0; 

public: 
. . . 
} 

推送功能,可以实现如下:

当你插入前增加MIN_STACK的价值,你总会留下堆叠[ 0]空了,浪费了空间。还可以使用MIN_STACK作为指标,而不是MAX_STACKMAX_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(); 
+0

谢谢!这清除了我几乎所有的疑惑:D – Bit89

一些随机的点,没有幌子是一个完整的清单。

class Stack // template <class Stack>

// void PUSH(int);
// void POP();

​​

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];
if(MIN_STACK > 0) { aux = stack[--MIN_STACK];