求助:vector做成员变量读入和写出文件出错

shanshuodexingyun 2009-07-15 10:24:11
#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

class Name
{
private:
int a;
int b;
vector<int> vc;

public:
Name();
Name(ifstream* f);

int random(int num);

void save(ofstream* f);

int getA();

};

#include "Name.h"

using namespace std;

const int NUM = 10;

Name::Name()
{
a = random(NUM);
b = a+10;
vc.push_back(a+100);
vc.push_back(b+100);
}
//读出文件把一个对象的成员变量用来初始化,构造函数
Name::Name(ifstream* f)
{
ar = new int[2];
f->read((char*)&a, sizeof(int));
f->read((char*)&b, sizeof(int));
for(int i =0; i<2; i++)
f->read((char*)&vc.at(i), sizeof(int));
}

//把所有成员变量保存到f里
void Name::save(ofstream* f)
{
f->write((char*)&a, sizeof(int));
f->write((char*)&b, sizeof(int));
for(int i =0; i<2; i++)
f->write((char*)&vc.at(i), sizeof(int));

}

//产生随机数
int Name::random(int num)
{
int arand = rand()%(num);
return arand;
}

int Name::getA()
{
return a;
}

#include "Name.h"
#include <time.h>
#include <stdlib.h>
using namespace std;

int main()
{
srand((unsigned)time(NULL));
int number = 10;
Name** inst = new Name*[number];
Name** insts = new Name*[number];
ofstream* ofile = new ofstream("output.txt");


for(int j = 0; j<number; j++)
inst[j] = new Name();

if(ofile->good())
{
for(int j = 0; j<number; j++)
{
inst[j]->save(ofile);
cout<<" * "<<inst[j]->getA();
}

}
ofile->close();
cout<<endl;

ifstream* ifile = new ifstream("output.txt");
if(ifile->good())
{
for(int j = 0; j<number; j++)
{
insts[j] = new Name(ifile);
cout<<" "<<insts[j]->getA();
}
}

return 0;
}


我的原意是将一组NAME的对象存到一个文件里,以后通过访问文件再读出这些对象到数组里
可是,我发现写入和读出来的值不同,不知道是不是因为成员变量含有vector导致的错误?
请高手解析,非常感谢!!


...全文
130 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
taodm 2009-07-15
  • 打赏
  • 举报
回复
你可以google 《汤姆 斯旺 编程秘诀》,里面有讲。
pengzhixi 2009-07-15
  • 打赏
  • 举报
回复
流对象用指针来传递,总感觉不妥啊!
shanshuodexingyun 2009-07-15
  • 打赏
  • 举报
回复
taodm,我google了序列化的定义,说是将对象状态变成可保持或传输的过程。
你提到的内部含指针的类型不可以用f->write,是不是说vector这样的变量不能这样存入文件呢,如果不可以,应该怎样来存入/读出呢?
taodm 2009-07-15
  • 打赏
  • 举报
回复
google 一下 序列化 吧。
内部含指针的类型都不可以直接fwrite的。
luhongyu2108 2009-07-15
  • 打赏
  • 举报
回复
f->write((char*)&vc.at(i), sizeof(int));
你存的是地址,下一次在运行的时候这个地址里的值当然和原来的不一样了

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧