0
這是來自我的.hpp文件。從主指針函數中打印出一個指針數組
struct Item{
std::string todo;};
const int MAX_STACK_SIZE = 5;
class StackArray
{
public:
StackArray();
bool isEmpty();
bool isFull();
void push(std::string Item);
void pop();
Item* peek();
int getStackTop() { return stackTop; }
Item** getStack() { return stack; }
private:
int stackTop;
Item* stack[MAX_STACK_SIZE];
};
#endif
以下是我的.cpp文件的一部分功能。
void StackArray::push(std::string Item)
{
if (isFull())
{
cout<<"Stack full, cannot add new todo item."<<endl;
}
else
{
stackTop++;
Item* newStack = new Item[MAX_STACK_SIZE];
newStack[stackTop].todo = Item;
}
}
我真的很困惑在main.cpp文件中打印堆棧數組。我怎樣才能做到這一點?現在我得到了,但只能打印出地址。
int main()
{
StackArray stackArray;
if (stackArray.isEmpty())
cout<< "Empty stack." <<endl;
stackArray.push("25");
stackArray.push("20");
stackArray.push("15");
stackArray.push("10");
Item**stack1=new Item*[5];
*stack1=new Item;
stack1=stackArray.getStack();
for(int i=0;i<5;i++)
{
cout<<*(stack1+i)<<endl;
}
}
你永遠不會在任何地方永久保存'newStack',所以你正在泄漏內存。 – Barmar
爲什麼你不只是將項目添加到'stack'? – Barmar
'cout < todo;'除了它可能會崩潰,因爲你從來沒有事實上初始化'StackArray :: stack'的內容;它包含隨機垃圾。 –