-1

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;
  }

main() は次のとおりです。

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

前もって感謝します !

4

1 に答える 1

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 のアイテムを返します。表示されるのは、最初の要素のアドレスではなく、初期化されていない 2 番目の要素の値です。

あなたがすべきことは次のとおりです。

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]);
    }
}
于 2013-03-13T00:22:53.330 に答える