我正在使用visual studio 2013.我的项目是图书管理系统 . 在阅读我的文件之后,访问声音除外 .
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:";
}
}
第3个Sem Final PROJECT.exe中0x6534DF58(msvcp120d.dll)的未处理异常:0xC0000005:访问冲突读取位置0x012D363C . 这是例外
1 回答
我们没有看到
Book
类的内容,但我强烈怀疑它使用的是非POD(纯对象数据)成员,如std::string
.在这种情况下,您无法使用与纯C类型相同的技术进行序列化并且最重要的是对对象进行反序列化 .
所以基本上,第一次,
b
没有用空值初始化/初始化,应该没问题,但是在file.read
调用之后,b
保持先前的b
状态,如果有std::string
对象,它会保留无效内存区域的指针(你会不会)尝试序列化指针?没有意义:这里也一样) .最简单的方法是在
Book
中编写适当的特定序列化/反序列化方法(例如通过重新定义operator<<
和operator>>
)