2014-11-08 62 views
-2

所以我有一个如下创建的堆栈。变量top应该表示当前索引或“最高索引”。所以通过做一些测试,构造函数确实调用了,而顶层的值是 -1,而程序仍在运行构造函数方法。但是,在创建堆栈对象和测试,看看有什么的顶部值后,我不断收到顶部32767字面上看,所有的主要的作用是创建一个新的堆栈为什么我的堆栈对象在创建后更改默认值?

Stack s; //Testing while this is running to see value of top... I get -1 
//Testing here to see value of top... I get 32767 

-

堆栈的创建方式如下所示。

#ifndef __STACK_H_ 
#define __STACK_H_ 

    class Stack{ 
    int stackSize; 
    int top; 
    char* items; 
    public: 
    Stack(); 
    ~Stack(); 
    void push(char c); 
    char pop(); 
    bool isFull(); 
    bool isEmpty(); 
}; 

#endif 

,如下列实现:

/* STACK IMPLEMENTATION FILE */ 

#include "stack.h" 
#include <iostream> 

using namespace std; 

Stack::Stack(){ 
    cout << "Ctor is run." << endl; 
    stackSize = 10; //Stack Size is 10 
    int top = -1; //Currently empty stack 
    cout << top << endl; 
    items = new char[stackSize]; 
} 

Stack::~Stack(){ //Destructor 
    delete[] items; 
} 

void Stack::push(char c){ //Push next into stack 
    items[++top] = c; 
    cout << top << endl; 
} 


char Stack::pop(){ //Pop one from stack 
    return items[top--]; 
} 

bool Stack::isFull(){ //Checks to see if stack is full 
    if (top + 1 == stackSize) return true; 
} 

bool Stack::isEmpty(){ //Checks to see if stack is empty 
    if (top == -1) return true; 
} 
+3

如果'if'测试失败,'isFull'和'isEmpty'不会返回任何东西。 – Barmar 2014-11-08 17:18:43

回答

4

你想top = 1在你的构造不int top = 1。前者分配给成员,后者初始化一个局部变量,在构造函数结束时超出范围。

+0

我花了几个小时试图弄清楚这个愚蠢的小错误。谢谢艾伦! – Jay 2014-11-08 17:27:34

相关问题