假设在一个程序的内存布局,我给出: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