【发布时间】:2013-11-23 15:46:53
【问题描述】:
我知道我不久前问过一个类似的问题,但它仍然不起作用。抱歉重复,我只是不确定为什么它不起作用。我创建了自己的链表(不使用 stl 库)我已经设置了我的类,并且可以按照我想要的方式完美地工作。当我使用函数填充列表时,我遇到的问题是获得参考。
在我的 main 中,我调用了用于填充列表的函数 bookSetUp()。我使这个函数等于一个临时指针。 (这里是代码)
Main.cpp
Book* temp = bookSetUp();
while(temp!=NULL)
{
cout<<temp->getName()<<endl;
cout<<temp->getAuthor()<<endl;
cout<<temp->getISBN()<<endl;
temp = temp->getNext();
}
bookSetUp() 位于另一个名为 functions.cpp的 .cpp 文件中(链接在两个 .cpp 之间有效,因为我已经对其进行了测试)
functions.cpp强>Book* bookSetUp()
{
//The items that populate the list
Book a("A Tale of Two Cities", "Charles Dickens", 1203456, true);
Book b("Lord of the rings", "J.R.R Tolkein", 123456, true);
Book c("Le Petit Prince", "Antoine de Saint-Exupéry", 123457, true);
Book d("And Then There Were None", "Agatha Christie", 123458, true);
Book e("Dream of the Red Chamber","Cao Xueqin",123459, true);
Book f("The Hobbit","J.R.R Tolkein",123467, true);
a.setPrev(NULL);
a.setNext(&b);
b.setPrev(&a);
b.setNext(&c);
c.setPrev(&b);
c.setNext(&d);
d.setPrev(&c);
d.setNext(&e);
e.setPrev(&d);
e.setNext(&f);
f.setPrev(&e);
f.setNext(NULL);
Book* temp = &a;
return temp;
}
如您所见,我正在尝试返回指向列表中第一项的指针,以便 main 可以访问它。我的书类具有以下属性:字符串名称、字符串作者、int isbn 和 bool 可用性。
程序崩溃,“bookRepository.exe 中 0x00B16886 处的未处理异常:0xC0000005:访问冲突读取位置 0xCCCCCD04。” 我猜这意味着它没有从 bookSetUp() 函数返回值。
同样在调试器中返回 int ISBN 但不返回字符串或布尔值。
有谁知道为什么这不起作用?如果可以的话,这将是一个巨大的帮助!
【问题讨论】:
标签: c++ function pointers linked-list