假設在一個程序的內存佈局,我給出:C++搞清楚成員編程
class Foo {
int x;
double y;
char z;
};
class Bar {
Foo f1;
int t;
Foo f2;
};
int main() {
Bar b;
bar.f1.z = 'h';
bar.f2.z = 'w';
... some crap setting value of b;
FILE *f = fopen("dump", "wb"); // c-style file
fwrite(&b, sizeof(Bar), 1, f);
}
假設在其他程序中,我有:
int main() {
File *f = fopen("dump", "rb");
std::string Foo = "int x; double y; char z;";
std::string Bar = "Foo f1; int t; Foo f2;";
// now, given this is it possible to read out
// the value of bar.f1.z and bar.f2.z set earlier?
}
什麼我問的是: 鑑於我有一個類的類型,我可以弄清楚C++如何顯示它?
1)您正在打開的「文本」模式的文件,使用二進制輸出功能'fwrite'。要小心,這在一些平臺上可行,但在其他平臺上不行。 2)一個類的成員默認是私有的,你必須使用'struct',或者聲明它們是公共的。 – AraK 2010-03-04 23:58:39
@Arak +1指出錯誤;這是否更好? – anon 2010-03-04 23:59:34