Class 堆栈实现(通过嵌套类)
我不确定我是否正确理解这个类是如何工作的。这是stack的一个例子Class 堆栈实现(通过嵌套类),class,c++-cli,stack,nested-class,Class,C++ Cli,Stack,Nested Class,我不确定我是否正确理解这个类是如何工作的。这是stack的一个例子 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 stac
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=gcnewitem(obj,Top)
因此基本上说Top
等于Next
。那么堆栈
类如何确定下一个
项,如果它总是堆栈顶部的项目呢?我认为您误解了这一行:
Top = gcnew Item(obj, Top);
这意味着:
- 使新项成为堆栈的顶部(这是堆栈的最终目标)
- 将新项目的
设置为以前的顶部Next
因此,通过调用
Top->Next
,您可以进入上一个项目(位于Top
下方的项目)我认为您误解了这一行:
Top = gcnew Item(obj, Top);
这意味着:
- 使新项成为堆栈的顶部(这是堆栈的最终目标)
- 将新项目的
设置为以前的顶部Next
Top->Next
,您可以进入上一个项目(位于Top
下方的项目)