struct point { float x, y; };
point D[800][600];
// ... 計算賦值 ...
ofstream ofile("D.txt");
for (int i=0; i<800; i++)
for (int j=0; j<600; j++)
ofile << D[i][j] << endl; // 編譯錯誤:無 operator<< 重載
ofile << D[i][j].x << ' ' << D[i][j].y << '\n';
struct point { float x, y; };
// 友元函數重載
friend ostream& operator<<(ostream& os, const point& p) {
return os << p.x << ' ' << p.y;
}
// 使用
ofile << D[i][j] << '\n'; // 現在合法
// 寫入
ofstream ofile("D.bin", ios::binary);
ofile.write(reinterpret_cast(D), sizeof(D));
// 讀取
ifstream ifile("D.bin", ios::binary);
ifile.read(reinterpret_cast(D), sizeof(D));
注意:二進制格式跨平台/編譯器可能有對齊/字節序差異,僅用於同環境臨時存儲。
struct point { float x, y; };
point D[800][600];
// 計算...
for (int I=0; I<800; I++) {
for (int J=0; J<600; J++) {
D[I][J].x = -1000.0f * 1 * (I-400) / 50;
D[I][J].y = -1000.0f * 1 * (J-300) / 50;
}
}
// 文本輸出(可讀)
ofstream ofile("D.txt");
for (int i=0; i<800; i++) {
for (int j=0; j<600; j++) {
ofile << D[i][j].x << ' ' << D[i][j].y << '\n';
}
}
ofile.close();
C++ 流對象**只內置基本類型**的 operator<<,**自定義類型必須自行實現**序列化邏輯(文本或二進制)。