【发布时间】:2017-11-11 23:33:04
【问题描述】:
尝试执行简单的任务。通过重载的提取运算符打开 ifstream 以从文本文件中读取。看起来不错,没有执行前错误。相信问题是由在这里使用指针引起的,但我没有看到问题。最后,我需要创建一个链表并使用重载的插入运算符输出到控制台。
使用 Visual Studio。 程序当前因以下异常而崩溃: 抛出异常:读取访问冲突。 这是 0xCCCCCCD0。
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
class Book {
public:
friend ostream& operator<< (ostream& out, Book* book) {
out << book->title_;
return out;
}
friend istream& operator>> (istream& in, Book* & book) {
getline(in, book->title_);
return in;
}
Book* setNext(Book* book) {
nextPtr_ = book;
return nextPtr_;
}
Book() : nextPtr_(NULL) {}
string getTitle() {
return title_;
}
Book* nextPtr_;
private:
string title_;
};
int main() {
ifstream inputFile;
Book *head;
inputFile.open("titles.txt");
// Creates head
head = new Book();
inputFile >> head;
Book* temp = head;
Book* newe;
for (int i = 0; i < 2; i++) {
inputFile >> newe;
cout << newe->getTitle();
temp->setNext(newe);
temp = temp->nextPtr_;
}
/*
for (int i = 0; i < 2; i++) {
cout << head << endl;
temp = head->nextPtr_;
}*/
system("PAUSE");
return 0;
}
【问题讨论】:
-
我没有看到这里分配了多少内存。
-
inputFile >> newe;这里,newe是一个未初始化的指针。因此,您的程序表现出未定义的行为。 -
你的指针和
new在 main 中过火了。你的教练可能告诉过你“使用指针”,但这并不意味着你会疯狂地使用它们。这个Book *newe;应该很可能是Book newe;,然后使用.运算符而不是->来访问newe元素。指针的使用可能应该与Book类中的nextPtr成员隔离。
标签: c++ pointers operator-overloading