带有指针的重载插入/提取运算符

Overloaded insertion/extraction operator with pointer

本文关键字:提取 运算符 插入 重载 指针      更新时间:2023-10-16

正在尝试执行简单的任务。打开 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;
}

为类实现流运算符的正确方法是通过引用而不是指针传递类对象:

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_; }
    ... 
};

然后在将Book*指针传递给运算符时取消引用它们:

inputFile >> *head;

inputFile >> *newe;
cout << *newe;

cout << *head << endl;

至于你的崩溃,那是因为你的newe指针在你传递给operator>>时是未初始化的。您需要在每次循环迭代中创建一个新的Book对象:

Book* newe;
for (int i = 0; i < 2; i++) {
    newe = new Book; // <-- add this! 
    inputFile >> *newe;
    ... 
}