私はこのコードをC++で.datファイルを作成するために使いました。C++でのファイル処理..どのように動作しますか?
これらの2行はわかりませんでした。これらはどのように機能しますか?
outfile.write(reinterpret_cast<char*>(&pers), sizeof(pers));
ofstream outfile("PERSON.DAT",ios::app| ios::binary);
#include <fstream> //for file streams
#include <iostream>
using namespace std;
class person //class of persons
{
protected:
char name[80]; //person’s name
short age; //person’s age
public:
void getData() //get person’s data
{
cout <<"Enter name: "; cin >> name;
cout <<"Enter age: "; cin >> age;
}
};
int main()
{
char ch;
person pers; //create a person
ofstream outfile("PERSON.DAT",ios::app| ios::binary);
do {
pers.getData(); //get data for person
outfile.write(reinterpret_cast<char*>(&pers), sizeof(pers));
cout <<"Enter another person (y/n)? ";
cin >> ch;
} while (ch == 'y');
//create ofstream object
//write to it
return 0;
}
「どのように機能しますか?」ひどく。シリアル化ライブラリを使用して物をシリアル化し、オブジェクトをバイトのパックとして扱わないでください。 –
構造体の整列は実装定義であるため、reinterpret_castを直列化に使用することは移植可能に動作することが保証されていません。 – moshbear
私はそれが何を意味するのかということでしたか? – zedai