读书人

c++怎么用输入输出流存取对象(或对象数

发布时间: 2012-03-16 16:34:56 作者: rapoo

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);

读书人网 >C++

热点推荐