问题描述
我目前正在使用 C++ 中的堆栈数据结构,我正在尝试使用数组初始化堆栈。 堆栈具有特定大小,我想使用 for 循环从 top 到 bottom 打印堆栈元素。 这是我的代码:
#include <iostream>
using namespace std;
template<class T>
class Stack {
private:
int top,size;
T* stack = new T[size];
public:
Stack(int size) {
this->top = -1;
this->size = size;
}
void push(int data) {
if (top >= size - 1) {
return;
}
else {
++top;
stack[top] = data;
}
}
void pop() {
if (top < 0) {
return;
}
else {
--top;
}
}
void print() {
for (int i = top; i >= 0; i--) {
cout << stack[i] << endl;
}
}
};
int main() {
Stack<int> stack(20);
stack.push(12);
stack.push(3);
stack.push(4);
stack.push(7);
stack.print();
return 0;
}
编译后,我成功打印了所有元素,但不幸的是,最后程序抛出异常ntdll.pdb not loaded。 提前致谢。
解决方法
构建顺序错误。成员变量在进入构造函数体之前被初始化,所以 size
包含一个任意值,当时它被读取以确定数组的大小。此外,您忘记删除数组。
为了修复初始化顺序,在构造函数中初始化数组并添加析构函数。在下面的代码中,我只是使用 std::unique_ptr
自动删除其中包含的数组。
此外,最好不要对参数和成员使用相同的标识符;为了避免这种情况,通常会在成员变量中添加前缀
#include <memory>
...
template<class T>
class Stack {
private:
size_t m_size;
int m_top;
std::unique_ptr<T[]> m_stack;
public:
Stack(size_t size)
: m_stack(new T[size]),m_size(size),m_top(-1)
{
}
...