c++怎么用流输入输出,将类的对象信息写到磁盘上?

来源:百度知道 编辑:UC知道 时间:2024/06/04 08:33:05
比如说:
class Time {
public:
Time(int h=0, int m=0, int s=0);
private:
int hour, minute, second;
};
定义Time类的对象a(12:00:00),请问怎么使用c++中的流输入输出将a的信息写到磁盘上?

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

class Time {
public:
Time(int h=0, int m=0, int s=0) { hour = h, minute = m, second = s; }
void store();
private:
int hour, minute, second;
};

void Time::store()
{
ofstream state("info.txt");

if (!state)
{
cerr << "Can't open file." << endl;
return;
}

state << hour << ' ' << minute << ' ' << second << endl;
state.close();
}

void main()
{
Time t(12, 10, 30);
t.store();
}

提供一种重载操作符的方式,仅供参考
#include<iostream>
#include<fstream>
using namespace std;

class Time;
ofstream& operator << (ofstream &of, Time &t);
class Time {
public:
Time(int h=0, int m=0, int s=0):hour(h),minute(m),second(s)