2017-11-11 2 views
-1

単純なタスクを実行しようとしています。 ifloadを開いて、オーバーロードされた抽出演算子を介してテキストファイルから読み込みます。上手く見え、実行前のエラーもありません。ここでポインタを使用することによって問題が発生していると考えていますが、この問題は表示されません。最後に、リンクリストを作成し、コンソールに出力するためにオーバーロードされた挿入演算子を使用する必要があります。ポインタを使用したオーバーロードされた挿入/抽出演算子

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; 
} 
+0

ここでは、割り当てられているメモリはそれほど多くありません。 – Bathsheba

+1

'inputFile >> newe;'ここで、 'newe'は初期化されていないポインタです。したがって、プログラムは未定義の動作を示します。 –

+0

あなたは、ポインタで外に出て、mainで 'new'を実行しています。あなたはおそらくあなたのインストラクターによって「ポインタを使う」と言われましたが、それはあなたが野生で狂っていることを意味しません。この 'Book * newe;'はおそらく 'Book newe;'であり、 'newe'要素にアクセスするために' - 'の代わりに' .'演算子を使います。ポインタの使用法は 'Book'クラスの' nextPtr'メンバに分離されているはずです。 – PaulMcKenzie

答えて

0

のクラスのストリーム演算子を実装するための正しいの方法は、ポインタによってクラスが参照の代わりによってオブジェクト渡すことですオペレータ:

inputFile >> *head; 
あなたのクラッシュについては

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

cout << *head << endl; 

あなたはoperator>>にそれを渡したときに、あなたのneweポインタが初期化されていないので、それはです。

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