【问题标题】:store private members as it is in c++, using write function使用写函数存储私有成员,就像在 C++ 中一样
【发布时间】:2012-03-30 10:33:33
【问题描述】:
class test{
    int x;
    public:
        //public functions getx() and putx()
};
void main()
{
fstream file;
test ob;
file.open("test.txt",ios::in|ios::out);
file.write((char *)&ob,sizeof(ob));
file.close();
}

执行此代码时,假设使用getx()函数将当前对象中x的值赋值为1,则与ascii值1对应的字符将存储在文本文件中,而不是数字1。如何解决这个问题?

【问题讨论】:

  • 你需要为你的类写一个序列化函数。
  • 将数字 1 转换为其对应的 ascii ?
  • 您所做的“按原样”存储私有成员,这当然不是整数的十进制表示,而是二进制格式。
  • 您可能想要升级您的编译器。据我所知,void main 不能在任何现代编译器上编译。
  • 我不明白你的问题是什么意思。

标签: c++


【解决方案1】:

你是用 getx() 分配 x 吗?我希望 putx(int x) 用于分配。在任何情况下,您都可以使用

将 int 写入文件
ofstream file;
...
file << (int)getx();

或者,就像@Oli Charleswoth 所说,编写一个序列化函数,在您的类中执行此操作。

与您的问题类似:Writing multiple variable types to a text file using ofstream

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-28
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    相关资源
    最近更新 更多