#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
class Student
{
private:
//私有成员变量
char name[10];
int age;
bool gender;
public:
Student()
{
}
Student(char* name,int age,bool gender):age(age),gender(gender)
{
//原型:
strcpy(this->name,name);
}
friend ostream& operator<<(ostream& o,const Student& s)
{
//为什么不直接把换行也搞定呢?因为做事情最好单一且专一,
//换行还是我们自己再重载函数外面来做。封装得太多反而不好。
return o << s.name << ',' << s.age << ',' << s.gender ;
}
};
int main()
{
//数组初始化对象
Student s[3] =
{
Student("aaa",20,true),
Student("bbb",21,true),
Student("ccc",19,false)
};
//ofstream ifstream
ofstream fout("stu.dat");
fout.write((const char*)s,sizeof(s));
fout.close();
//会不会创建对象?
Student s2[3];
ifstream fin("stu.dat");
fin.read((char*)s2,sizeof(s2));
for(int i = 0; i < 3; i++)
{
cout << s2[i] << endl;
}
fin.close();
}
数组初始化对象,ifstream,ofstream
最新推荐文章于 2023-11-07 09:05:12 发布