2011-09-03 69 views
1

即时通讯不知道如果我正确理解这个类是如何工作的。它是一个堆栈的例子。栈实现(通过嵌套类)

ref class Stack 
{ 
    private: 

     ref struct Item // Defines items to store in the stack 
     { 
     Object^ Obj; // Handle for the object in this item 
     Item^ Next; // Handle for next item in the stack or nullptr 

     Item(Object^ obj, Item^ next): Obj(obj), Next(next){} // Constructor 
     }; 

     Item^ Top; // Handle for item that is at the top 

    public: 

     void Push(Object^ obj) // Push an object onto the stack 
     { 
     Top = gcnew Item(obj, Top); // Create new item and make it the top 
     } 

     Object^ Pop() // Pop an object off the stack 
     { 
     if(Top == nullptr) // If the stack is empty 
     return nullptr; // return nullptr 
     Object^ obj = Top->Obj; // Get object from item 
     Top = Top->Next; // Make next item the top 
     return obj; 
     } 
}; 

我不知道推功能如何工作。在类定义中它的Top=gcnew Item(obj, Top)所以基本上它说Top等于Next。那么Stack类如何确定Next项,如果它始终位于栈顶?

回答

1

我认为你曲解行:

 Top = gcnew Item(obj, Top); 

这意味着:

  • 使新项目的堆栈的顶部(这是最终你想要的堆栈)
  • 将新项目的Next设置为之前最高的项目

所以通过调用Top->Next你到前一个项目(“底下”Top

+1

谢谢,x0r。现在对我来说很有意义。 –