首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

c++怎么用输入输出流存取对象(或对象数组)的数据成员

2012-03-16 
c++如何用输入输出流存取对象(或对象数组)的数据成员?#include iostream#include string#include fst

c++如何用输入输出流存取对象(或对象数组)的数据成员?
#include <iostream>
#include <string>
#include <fstream>
using   namespace   std;

class   Stu_Info
{
private:
      string   name;
      int   age;;
      int   number;
public:
      //
      //
      void   setname(string   str){name=str;}
      void   setage(int   ages){age=ages;}
      void   setnumber(int   num){number=num;}
};
int   main()
{
Stu_Info   *ptr=new   Stu_Info;
ptr-> setname( "lihua ");
ptr-> setage(18);
ptr-> setnumber(310);
ofstream   ofile( "stuinfo.dat ",ios_base::out);
ofile.write((char*)ptr,sizeof(*ptr));   //***************//
ofile.close();
cout < < "信息已经保存! " < <endl;
delete   ptr;
}
请问,打*****号那一行符合c++规范吗?

[解决办法]
经典做法重载operator < <
friend ostream& operator < <(ostream & os, const Stu_Info& inst)
{
os < <inst.name < <inst.age < <inst.number;
return os;
}
...
ofile < <(*ptr);

热点排行