2015-11-08 208 views
-2

我写了一个简单的程序来学习如何使用随机访问填充。它编译良好,但在运行时会导致访问冲突错误。我只写和阅读单个记录。C++访问冲突错误

头文件:

#include<iostream> 
#include<string> 
#include<fstream> 
using namespace std; 

#ifndef HEADER_H 
#define HEADER_H 


class info 
{ 
private: 
    int id; 
    string name; 
public: 
    info(int = 0, string = " "); 
    void set(int, string); 
    void display(); 
    void write(); 
    void read(); 
}; 

#endif 

执行文件:

#include<iostream> 
#include<string> 
#include<fstream> 
#include"Header.h" 
using namespace std; 

info::info(int x, string y) 
{ 
    set(x, y); 
} 

void info::set(int x, string y) 
{ 
    id = x; 
    name = y; 
} 

void info::display() 
{ 
    cout << "\n\n\tid : " << id; 
    cout << "\n\tname" << name; 
} 

void info::write() 
{ 
    ofstream o("info.dat", ios::out | ios::binary | ios::app); 
    info a(id, name); 
    info *p = &a; 
    o.write(reinterpret_cast<const char *>(p), sizeof(info)); 
    o.close(); 
    cout << "\n\n\tWrite Successful"; 
} 

void info::read() 
{ 
    ifstream i("info.dat", ios::in | ios::binary); 
    i.seekg(0); 
    info a(0, "a"); 
    info *p = &a; 
    i.read(reinterpret_cast<char *>(p), sizeof(info)); 
    i.close(); 
    p->display(); 
    cout << "\n\n\tRead Successful"; 
} 

主:

#include<iostream> 
#include<string> 
#include<fstream> 
#include"Header.h" 
using namespace std; 

void main() 
{ 
    info a(10, "muaaz"); 
    a.write(); 
    a.display(); 
    info b(2, "m"); 
    b.read(); 
} 

错误Ô在读取函数后发生。读取函数结束时的“读取成功”结果运行良好,之后在主文件中没有其他语句。我不知道是什么导致了错误。

+0

你的程序有问题,调试它。 –

+0

请阅读SO指导原则,您应该提供一个最小但完整的示例。 –

+4

'std :: string'是一个非pod类。您无法保存并将其恢复到您想要执行的二进制文件。 –

回答