-1
간단한 작업을 수행하려고합니다. 오버로드 된 추출 연산자를 통해 텍스트 파일에서 읽을 ifstream 열기. 보기 좋고 사전 실행 오류가 없습니다. 여기에 포인터를 사용하면 문제가 발생한다고 생각하지만 문제가 보이지 않습니다. 결국 연결 목록을 만들고 과부하 삽입 연산자를 사용하여 콘솔에 출력해야합니다.포인터로 삽입/추출 연산자가 오버로드 됨
Visual Studio 사용. 예외가 발생하여 프로그램이 현재 충돌하고 있습니다. 읽기 액세스 위반입니다. 이것은 0xCCCCCCD0입니다. 로 전달 할 때 Book*
포인터 역 참조 그런
class Book {
public:
friend ostream& operator<< (ostream& out, const Book &book) {
out << book.title_;
return out;
}
friend istream& operator>> (istream& in, Book &book) {
getline(in, book.title_);
return in;
}
...
string getTitle() const { return title_; }
...
};
:
#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;
}
여기에 할당 된 메모리가별로 없습니다. – Bathsheba
'inputFile >> newe;'여기서 newe는 초기화되지 않은 포인터입니다. 따라서 프로그램은 정의되지 않은 동작을 보입니다. –
당신은 포인터로'main'에서'new'를 보냅니다. 강사가 "포인터 사용하기"라는 말을 들었을 지 모르지만, 그렇다고해서 자연스럽고 미친 말은 아닙니다. 이'Book * newe;'는'Book newe '가되어야하고,'newe' 엘리먼트에 접근하기 위해'-'대신'.' 연산자를 사용하십시오. 포인터 사용법은'Book' 클래스의'nextPtr' 멤버와 격리되어 있어야합니다. – PaulMcKenzie