所以我一直在学习用 C++ 制作堆栈的教程(这里),我相信我逐行复制了他的代码行,但我一直收到这个未处理的异常错误。我在想它与指针有关,但在搜索我的程序后,我无法识别任何被不当访问的指针。确切的错误消息是:“Project50.exe 中 0x00D45446 处的未处理异常:0xC0000005:访问冲突读取位置 0x00000014。” 程序输出是第 4 次推送,但前三个都没有(屏幕上出现的内容,除了空格应该是虚线,但这会导致帖子格式化为粗体):
名称:水值:3
弹出
姓名:
我正在使用 Visual Studio 2012,而做本教程的人正在使用 Netbeans IDE。这可能是权限问题吗?
头文件:
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
class Stack {
private:
struct item {
string name;
int value;
item* prev;
};
item* stackPtr;
public:
void Push(string name, int value);
void Pop();
void ReadItem(item* r);
void Print();
Stack();
~Stack();
};
堆栈实现:
#include "Header.h"
using namespace std;
Stack::Stack() {
stackPtr = NULL;
}
Stack::~Stack() {
item* p1;
item* p2;
p1 = stackPtr;
while( p1 != NULL) {
p2 = p1;
p1 ->prev;
p2->prev = NULL; // Not actually necessary, but distinguishes that p1 and p2 are pointing to different things
delete p2;
}
}
void Stack::Push(string name, int value) {
item* n = new item;
n->name = name;
n->value = value;
if(stackPtr = NULL) { // For first item of the stack
stackPtr = n;
stackPtr->prev = NULL; // So that the item at the bottom of the stack points to null
}
else {
n->prev = stackPtr;
stackPtr = n;
}
}
void Stack::ReadItem(item* r) {
cout << "-------------------------\n";
cout << "name: " << r->name << endl;
cout << "value: " << r->value << endl;
cout << "-------------------------\n";
}
void Stack::Pop() {
if(stackPtr = NULL) {
cout << "There is nothing on the stack\n";
}
else {
item* p = stackPtr;
ReadItem(p);
stackPtr = stackPtr->prev;
p->prev = NULL; // Again, like the one in the destructor, not actually necessary.
delete p;
}
}
void Stack::Print() {
item* p = stackPtr;
while(p != NULL) {
ReadItem(p);
p = p->prev;
}
}
主要的:
#include "Header.h"
using namespace std;
int main(int argc, char** argv) {
Stack Dan;
Dan.Push("Dan", 3);
Dan.Push("Coffee", 1);
Dan.Push("Donuts", 0);
Dan.Push("Water", 3);
Dan.Print();
cout<< "Popping\n";
Dan.Pop();
cout<< "Popping\n";
Dan.Pop();
cout<< "Popping\n";
Dan.Pop();
cout<< "Popping\n";
Dan.Pop();
cout<< "Popping\n";
Dan.Pop();
cout << '\n';
system("PAUSE");
return 0;
}