从保存的文件初始化类
在 Objective-C++ 中,我希望我的应用程序能够保存和加载表示某些 C++ 对象存在的文件。例如,用户正在运行应用程序并创建了类 A
的对象 a
、b
和 c
、B
和 C
。用户点击“保存”来创建一个文件,以某种格式列出这些对象。然后,应用程序应该能够从此文件加载并初始化类 A
x、y
和 z
的新对象code>、B
和 C
通过调用构造函数 A()
、B()
和 C()
。 (这显然是对流程的极大简化。)
您认为执行此操作的最佳策略是什么?有没有比将文本映射到构造函数或类似的大型 switch 语句更优雅的解决方案?函数指针可以帮助我吗?我可以想象做一些事情,比如让 A
、B
和 C
向拥有它们的对象注册自己,并用一个某个地方的关键,但我想知道是否有一些简单的东西我丢失了。
这里的大问题是必须保存数十个类,因此我希望尽可能采用最轻的解决方案。
In Objective-C++, I want my application to be able to save and load files that express the existence of certain C++ objects. For example, a user is running the application and has created objects a
, b
, and c
of classes A
, B
, and C
. The user hits save to create a file that lists these objects in some format. The application should then be able to load from this file and initialize new objects x
, y
, and z
of classes A
, B
, and C
by calling constructors A()
, B()
, and C()
. (This is obviously a heavy simplification of the process.)
What do you think is the best strategy for doing this? Is there any more elegant solution than a big switch statement mapping text to constructors or something along those lines? Would function pointers help me out? I could imagine doing something like having A
, B
, and C
register themselves with the object that owns them, and it stores their constructors with a key somewhere, but I'm wondering if there's something simple that I'm missing.
The big issue here is that there are dozens of classes that must be saved so I want the lightest solution possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
继我刚刚对您的帖子发表的评论之后,该文章对 Objective-C 进行了以下说明:
“在 Objective-C 编程语言中,序列化(更常见的称为归档)是通过重写
write:< Object 根类中的 /code> 和
read:
方法。”我自己只是 Objective-C 的新手,但我熟悉序列化的概念。在这种情况下,通过重写这些方法,您可以使给定类型的对象能够以您指定的格式将自身写入文件,并且还允许它通过从文件中读取其状态来设置其状态。
我相信谷歌会透露很多这方面的教程。
Following up on the comment I just put on your post, that article states the following regarding Objective-C:
"In the Objective-C programming language, serialization (more commonly known as archiving) is achieved by overriding the
write:
andread:
methods in the Object root class."I'm only new to Objective-C myself, but I'm familiar with the concept of serialization. In this case, by overriding those methods, you are making an object of a given type capable of writing itself to a file in a format you specify, and also you are allowing it to set its state by reading its state from a file.
I'm sure Google will reveal a lot of tutorials on this.