2016-12-31 102 views
-1

我正在使用visual studio 2013.我的项目是图书馆管理系统。读取我的文件后,它是访问voilation的例外。 0000005:在0x6534DF58(msvcp120d.dll)在第3扫描电镜决赛PROJECT.exe访问冲突读取位置0x012D363C

class Book { 

    string edition; 
    string serialno; 
    string shelfno; 
    int date, month, year; 

public: 
    Book(); 
    Book(char name, char aname, string edit, int srno, int shfno); 
    void getbook(); 
    void showbook(); 
    void getdate(); 
    string bookname; 
    string authorname; 
}; 

Book::Book() 
{ 
    bookname = "BOOKNAME"; 
    authorname = "AUTHORNAME"; 
    edition = "EDITION"; 
    serialno = "SERIALNO."; 
    shelfno = "SHELFNO."; 
} 

void Book::showbook() 
{ 
    cout << bookname << " ---- " << authorname << " ---- " << edition << "---- " << serialno << "----" << shelfno << endl; 
} 

void Librarysystem::showrecord() 
{ 
    ifstream file; 

    Book b; 
    file.open("bookrecord.txt", ios::in); 
    if (!file) 
     cerr << "\n could not open file:"; 
    cout << "\t\t BOOK RECORD\n\n" << endl; 
    while (!file.eof()) { 
     b.showbook(); 
     file.read(reinterpret_cast<char*>(&b), sizeof(b)); 

     if (file.eof()) 
      file.close(); 
     //cerr << "\n could not read from file:"; 
    } 
} 

未处理的异常访问冲突读取位置0x012D363C。 这是例外

+0

你不能反序列化这样的对象,如果它们不包含POD-唯一成员。你能告诉我们“Book”的定义吗? –

+1

本书当然不是POD类型..从来没有保存对象的状态,保存它的字段值。你需要在课堂上的序列化方法 – Swift

+1

请学会缩进你的代码;它可以帮助我们进行调试,它也可以帮助您*。 – cybermonkey

回答

1

我们没有看到Book类的内容,但我强烈怀疑它使用的是非POD(纯对象数据)成员,如std::string

在这种情况下,您的不能序列化,并且大部分都使用与纯C类型一起使用的相同技术对对象进行反序列化。

while (!file.eof()) 
{ 
    b.showbook(); 
    file.read(reinterpret_cast<char*>(&b), sizeof(b)); 

因此,基本上,第一次,b未初始化/空值初始化,应该OK,但file.read电话后,b持有以前b状态,如果有std::string对象,其持有的指针在无效的内存区域(你会尝试序列化一个指针?没有意义:在这里也一样)。

简单的方法是写适当&特定序列化/反序列化方法Book(通过重新定义operator<<operator>>例如)

+0

更好的是定义运算符<< – Swift

相关问题