C ++将对象写入文件,然后稍后将其读入? [英] C++ writing an object to a file then later reading it in?

查看:62
本文介绍了C ++将对象写入文件,然后稍后将其读入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何在c ++中进行序列化?
如何在C ++中实现序列化

这些天来,我一直在越来越多地使用C ++,在这一点上,我只对ofstream有过几次经验.多数上述经验是对变量进行简单的文件输出,然后将其与ifstream一起读回.我还没做的是处理对象.

I've been toying around with C++ more and more these days and have only had a couple experiences with ofstream at this point. Most of said experiences have been doing simple file output of variables and reading them back in with ifstream. What I haven't done is anything with objects.

让我们假设我有一个经常被写入的对象(例如,一个游戏,而该对象就是角色).每次击中该角色,都会重新编写马力,每当他们击败一个敌人时,它们都是积累经验....我的基本想法是编写一个简单的基于文本的地牢爬行游戏.但是我该如何制作某种自动保存文件呢?我是否只是将对象的每个属性分别写到文件中,然后从那里移到更大更好的文件上?如果我现在必须这样做,那就是我要去做的方式,但是我忍不住想要感觉有比这更简单的方法了…….

Let's assume that I have an object that is being written to frequently (say a game, and the object is the character) Every time the character is hit, the hp is re-written, every time they defeat an enemy they are gaining experience.... my basic idea is to write a simple text-based dungeon crawling game. But how am I going to make some kind of an autosave file?? Do I just write out every attribute of my object to a file individually and then move onto bigger and better from there? If I had to do it right now that's how I'd go about doing it, but I can't help like feeling that there's an easier way than that....

有人愿意帮助我将整个对象的内容(及其各自的属性)输出到文件吗?

Anyone care to help me output the contents of an entire object(and it's respective attributes) to a file?

推荐答案

您可以通过将对象的内容复制到内存中来将其写入文件.

You could just write the object to a file by copying it's contents in memory.

但随后您就遇到了棘手的问题!您不能复制任何指向内存的指针,因为当您将它们加载回内存时,它们并不拥有该内存.这意味着复制诸如std :: string之类的内容可能内部包含其自身的内存分配也很棘手.

But then you hit the tricky bits! You can't copy any items that are pointers to memory, because when you load them back in they don't own that memory. That means copying things like std::string which may internally contain their own memory allocation is also tricky.

然后,即使对于标准类型,如果您打算在具有不同位数或字节顺序的另一台机器上读取它们,也会出现问题.

Then even with standard types there are issues if you plan to read them on a different machine with a different number of bits, or a different byte order.

该过程称为序列化-有一些标准技术可以使操作变得更容易.

The process is called serialisation - there are a few standard techniques to make it easier.

这篇关于C ++将对象写入文件,然后稍后将其读入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆