C ++ Access错误,指针麻烦

时间:2018-04-28 20:33:47

标签: c++ pointers

我正在努力将对象保存到文件中并将其读回。现在我正试图一次做一个,看我是否可以做,避免重复的对象。我收到此错误:Exception thrown at 0x00915B18 in who.exe: 0xC0000005: Access violation writing location 0xDDDDDDDD

我知道这是因为我没有正确使用指针做某些事情,但我已经迷失了,无法弄明白,目前的代码是:

#include<iostream>
#include "Book.h"
#include "InventoryBook.h"
#include "SoldBook.h"
#include<string>
#include<fstream>
using namespace std;

void saveBook(Book);
Book returnBook();

void main() {

    Book novel;
    InventoryBook shelf;
    SoldBook gone;
    novel.setAuthor("Joe");
    novel.setISBN("1234567788");
    novel.setPublisher("Me");
    novel.setTitle("Joe vs. the Volcano");

    saveBook(novel);
    Book rBook = returnBook();
    cout << rBook.getAuthor(); 

    system("Pause");
}

void saveBook(Book saved) {
    ofstream myfile;

    myfile.open("bookInventory.txt", ios::app);

    myfile.write((char*)&saved, sizeof(saved));

}

Book returnBook() {
    ifstream myfile;

    myfile.open("bookInventory.txt", ios::in);

    Book novel;
    Book newBook;

    myfile.read((char*)&novel, sizeof(novel));

    newBook.setAuthor(novel.getAuthor());


    return newBook;
}

我知道保存书功能有效,而且我遇到了返回的书籍对象的问题。我只是无法看到这出错的地方。我对指针有点模糊。

#pragma once
#ifndef BOOK_H
#define BOOK_H
#include<iostream>
using namespace std;


class Book{

private:
    string ISBN;
    string bookTitle;
    string authorName;
    string publisher;

public:
    Book(string, string, string, string);
    Book();
    //destructor
    ~Book();
    //Mutators
    void setTitle(string);
    void setISBN(string);
    void setAuthor(string);
    void setPublisher(string);
    //accessors
    string getTitle();
    string getISBN();
    string getAuthor();
    string getPublisher();

};

#endif
#include "Book.h"


Book::Book() {
    ISBN = "";
    bookTitle = "";
    authorName = "";
    publisher = "";
}

Book::Book(string newISBN, string newTitle, string newAuthor, string newPub) {

    ISBN = newISBN;
    bookTitle = newTitle;
    authorName = newAuthor;
    publisher = newPub;
}

Book::~Book()
{
}

void Book::setISBN(string newISBN) {
    ISBN = newISBN;
}

string Book::getISBN() {
    return ISBN;
}

void Book::setTitle(string newTitle) {
    bookTitle = newTitle;
}

string Book::getTitle() {
    return bookTitle;
}

void Book::setAuthor(string newAuthor) {
    authorName = newAuthor;
}

string Book::getAuthor() {
    return authorName;
}

void Book::setPublisher(string newPub) {
    publisher = newPub;
}

string Book::getPublisher() {
    return publisher;
}

0 个答案:

没有答案