C++如何根据要写入的数据类型动态选择文件句柄?

发布于 11-28 04:20 字数 824 浏览 1 评论 0原文

我有一个 class outputInterface; ,它应该处理一些数据的输出(到文件)。数据包含在一些自定义类的对象中,例如 dataClassAdataClassB,它们都派生自公共基类 dataClassBase

现在我希望数据根据其类型写入不同的文件。因此,dataClassA 类型的数据应转到 fileAdataClassB 类型的数据应转到 fileB,依此类推。由于此输出经常发生,我希望文件句柄(fileAfileB)保持打开状态,即我不想打开和关闭输出文件每一条数据。可以预期一个 outputInterface 对象始终存在。

所以我想实现的是这样的:

  • 动态地将 dataClassA 类型的数据与文件句柄 fileA 等相关联。
  • 当接收 dataClassA 类型的数据时code> 检查fileA是否已连接到文件,如果没有,则打开该文件。

我怎样才能得到这种行为(或者至少类似/更好的行为)? 我一直在考虑使文件处理 dataClassAdataClassB (或基类 dataClassBase?)的静态成员。但是,我该如何关闭这些文件呢?我必须以某种方式跟踪实际使用的数据类型(实际打开的文件)。

I've got a class outputInterface; that should handle the output (to files) of some data. The data is contained in objects of some custom classes, say dataClassA and dataClassB, that all derive from a common base class dataClassBase.

Now I want the data to be written to different files according to its type. So data of type dataClassA should go to fileA, data of type dataClassB should go to fileB and so on. As this output happens very often I would like the file handles (fileA and fileB) to stay open, i.e. I don't want to open and close the files for the output of each piece of data. One outputInterface object can be expected to exist all the time.

So what I would like to achieve is something like this:

  • Dynamically associate data of type dataClassA with the file handle fileA etc.
  • When receiving data of type dataClassA check whether fileA is already connected to a file, if not, open the file.

How can I get this behavior (or least something similar / better)?
I've been thinking of making the file handles static members of dataClassA and dataClassB (or the base class dataClassBase?). But then, how do I take care of closing the files? I would have to somehow keep track of the data types that have actually been used (the files that have actually been opened).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文