alp*_*pho 3 c++ stack pointers
我正在学习C++,我们接受了练习,使用类模板和指针创建堆栈类.我还没有完全理解堆栈或指针的实现,所以我给它一个去做了这个类:
template <class T>
class Stack_Class {
public:
T* stack;
int item_quantity;
T* First_item;
int Max_quantity;
Stack_Class(int value);
~Stack_Class();
bool Add(T value);
T Pop();
int GetMax_Quantity();
bool Full();
bool Empty();
};
template <class T>
Stack_Class<T>::Stack_Class(int value) {
if (value > 0) {
stack = new T[value];
First_item = stack;
item_quantity = 0;
Max_quantity = value;
}
}
template <class T>
Stack_Class<T>::~Stack_Class() {
if (First_item) {
delete First_item;
}
}
template<class T>
bool Stack_Class<T>::Add(T num) {
if (item_quantity <Max_quantity) {
*stack = num;
stack++;
item_quantity++;
return true;
}
else return false;
}
template<class T>
T Stack_Class<T>::Pop() {
if (!Empty()) {
item_quantity--;
return stack[item_quantity];
}
return NULL;
}
template<class T>
bool Stack_Class<T>::Empty() {
return (item_quantity == 0);
}
template <class T>
int Stack_Class<T>::GetMax_Quantity() {
return Max_quantity;
}
Run Code Online (Sandbox Code Playgroud)
主要课程将是:
#include <iostream>
#include "Stack_Class.h"
void main() {
Stack_Class<int> intStack(3);
intStack.Add(1);
intStack.Add(2);
intStack.Add(3);
int count = intStack.GetMax_Quantity();
for (int i = 0; i < count; i++) {
std::cout << "Pop No: " << i << " - Elemento: " << intStack.Pop() << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
虽然结果我得到所有随机数而不是我在intStack中给出的那些数.添加,所以我的问题是我正在这里正确实现指针?
stack在引用指针之前,需要先递减指针Pop():
template<class T>
T Stack_Class<T>::Pop(){
if (!Empty()){
item_quantity--;
stack--;
return *stack;
}
return NULL;
}
Run Code Online (Sandbox Code Playgroud)
您的数组访问stack[item_quantity]不起作用,因为您增加stack了Add.所以在构造之后,指向的内存stack看起来像这样
0xff65f96f <-- *(stack + 0)
0x0eec604f <-- *(stack + 1)
0x05be0582 <-- *(stack + 2)
0x29b9186e <-- *(stack + 3)
Run Code Online (Sandbox Code Playgroud)
十六进制值表示在分配时同时位于存储器中的随机垃圾.这是因为分配的内存new未初始化为好的东西.添加三个值后,它看起来像这样
1 <-- *(stack - 3)
2 <-- *(stack - 2)
3 <-- *(stack - 1)
0x29b9186e <-- *(stack + 0)
0xf66eff06 <-- *(stack + 1)
0x357eb508 <-- *(stack + 2)
Run Code Online (Sandbox Code Playgroud)
在第一次调用中Pop,您可以访问stack[2] = *(stack + 2),因为item_quantity在减去它之后是2.连续两次调用Pop访问stack[1]和stack[0].正如您在上面所看到的,您实际上从未实际引用您放入堆栈的值.