我正在制作一个由节点组成的通讯录。
我的目标是打印链表(从头到尾) 并通过下面的 SaveContacts 方法写入文本文件。
这两个方法都是我节点类的一部分。
但是,无论我是否包含 try/catch/throw 调用,我都会收到访问冲突异常。
确切错误:
Unhandled exception thrown: read access violation.
this->current was 0xCDCDCDCD.
我简要研究了访问冲突异常,发现通常这是一种不好的做法,只有少数异常(exception)。
我尝试将编译器选项从 Ehs 更改为 Ehsc。两者都导致相同的错误。
Node.h
class ContactBook
{
private:
public:
// Pointers necessary for travesal and construction
// of the linked list
AddressNode *head = nullptr;
AddressNode *tail = nullptr;
AddressNode *current = nullptr;
AddressNode *newContact = nullptr;
// Methods to add and print contacts
void PrintForward();
void InsertAtEnd();
// Method to Save Contacts in a text file
void SaveContacts();
ContactBook();
~ContactBook();
};
节点.cpp
将节点插入链表
void ContactBook::InsertAtEnd()
{
newContact = new AddressNode;
newContact->CreateContact();
if (head == nullptr)
{
head = newContact;
//head->prev = nullptr;
tail = newContact;
}
else
{
tail->link = newContact;
tail = newContact;
tail->prev = tail;
}
}
访问冲突异常发生在这里 有或没有 try/catch/throw
打印方法(与SaveContacts方法基本相同)
void ContactBook::PrintForward()
{
try
{
throw current = head;
}
catch (...)
{
while (current->link != nullptr)
{
current->PrintContactList();
cout << endl;
current = current->link;
}
}
}
写入文件方法(与PrintForward方法基本相同)
void ContactBook::SaveContacts()
{
throw current = head;
try
{
// Honestly don't know what to insert here
}
// To catch any exception
catch (...)
{
fstream file;
file.open("SavedContacts.txt", ios::out);
while (current->link != nullptr)
{
file >> current->PrintContactList();
current = current->link;
}
file.close();
}
}
main.cpp
#include "AddressNode.h"
#include "ContactBook.h"
#include <fstream>
int main()
{
ContactBook contactBook;
for (int i = 0; i < 5; i++)
{
contactBook.InsertAtEnd();
cout << "Hello, " << contactBook.newContact->GetName() << endl;
cout << contactBook.newContact->PrintContactList();
}
system("cls");
///////////////////////////
// EXCEPTION HANDLING????//
///////////////////////////
contactBook.PrintForward();
cout << "The end \n";
//contactBook.SaveContacts();
system("pause");
return (0);
}
有人可以根据下面提供的代码提出可行的解决方案吗?
最佳答案
首先,您对使用异常处理的理解是错误的。一个有效序列的例子是:
try{
code that might throw an exception
}
catch(exception){
exception handling code
}
您的实现在错误的 catch 子句中进行了处理。将代码移至 try block 。 insertAtTheEnd 函数似乎有效,但将“尾部”链接到前一个元素的方式是错误的。正确的做法是:
tail->link = newContact;
newContact->prev=tail;
tail = newContact;
要解析您的联系人列表,您可以使用类似于:
current=head; //init the pointer with the head of the list
while (current != nullptr) //check if you have not reached the end of the list
{
//process the current node
current = current->link;
}
我不保证这会解决您的问题,但这将是朝着正确方向迈出的一步。
关于c++ - 链接列表的访问冲突异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44581526/