堆栈模板 - pop函数返回地址而不是值

时间:2013-03-13 00:08:58

标签: c++ templates stack

我正在尝试使用C ++中的模板创建一个堆栈,一切正常,对于Pop函数来说,它返回项目的地址而不是实际值,代码如下。

 template <typename T>
 class Stack {

const int size;
T* data;
int index;

public:
    Stack(){};
    Stack (const int S);
    ~Stack(){delete [] data;};
    bool Push (const T& info);
    T Pop ();
    bool is_empty();
};

 template <typename T>
 Stack <T> ::Stack (const int S) : size(S)  // Stack CTOR
 {
  this->data = new T [this->size];
  this->index=0;
 }

 template <typename T>
 bool Stack<T> ::Push (const T& info)
 {  

  if(index==(size-1))
            return false;
   else{
      this->data[index] = info;
      index++;
      return true;}
 }


template <typename T>
T Stack <T> ::Pop ()
{       
    index--;
    return (this->data[index+1]);
} 

 template <typename T>
 bool Stack<T> ::is_empty()
 {
  if(index==0){return true;}
        else
            return false;
  }

主要的()是:

Stack <int> Sint (10);
Sint.Push(6);
int X = Sint.Pop();
cout<<X;  // prints out the address and not the value

提前感谢!

1 个答案:

答案 0 :(得分:1)

下面:

 template <typename T>
 bool Stack<T> ::Push (const T& info)
 {
     if (index == (size-1))
     {
         return false;
     }
     else
     {    
         this->data[index] = info;
         index++; // index becomes 1 after the first insertion...
         return true;
     }
 }

如果堆栈为空,则将项目存储在索引0处,增加索引,然后变为1.然后在此处:

template <typename T>
T Stack <T> ::Pop ()
{
    index--; // index becomes 0...
    return (this->data[index+1]); // returning the uninitialized item at
                                  // index 0 + 1 = 1...
}

您正在减小索引,该索引变为0,然后返回索引1处的项目,该项目从未分配过。您看到的内容不是第一个元素的地址,而是未初始化的第二个元素的值。

你应该做的是:

template <typename T>
T Stack <T> ::Pop ()
{
    if (index == 0)
    {
        // Maybe throw an exception?
        // You should handle the error condition somehow.
        return T();
    }
    else
    {
        index--;
        return (this->data[index]);
    }
}