【问题标题】:Overloaded insertion/extraction operator with pointer带指针的重载插入/提取运算符
【发布时间】: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 &gt;&gt; newe; 这里,newe 是一个未初始化的指针。因此,您的程序表现出未定义的行为。
  • 你的指针和 new 在 main 中过火了。你的教练可能告诉过你“使用指针”,但这并不意味着你会疯狂地使用它们。这个Book *newe; 应该很可能是Book newe;,然后使用. 运算符而不是-&gt; 来访问newe 元素。指针的使用可能应该与Book 类中的nextPtr 成员隔离。

标签: c++ pointers operator-overloading


【解决方案1】:

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

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&gt;&gt; 时,它未初始化。您需要在每次循环迭代时创建一个新的 Book 对象:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 2012-05-10
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多