C++如何根据要写入的数据类型动态选择文件句柄?
我有一个 class outputInterface;
,它应该处理一些数据的输出(到文件)。数据包含在一些自定义类的对象中,例如 dataClassA
和 dataClassB
,它们都派生自公共基类 dataClassBase
。
现在我希望数据根据其类型写入不同的文件。因此,dataClassA
类型的数据应转到 fileA
,dataClassB
类型的数据应转到 fileB
,依此类推。由于此输出经常发生,我希望文件句柄(fileA
和 fileB
)保持打开状态,即我不想打开和关闭输出文件每一条数据。可以预期一个 outputInterface
对象始终存在。
所以我想实现的是这样的:
- 动态地将
dataClassA
类型的数据与文件句柄fileA
等相关联。 - 当接收
dataClassA
类型的数据时code> 检查fileA
是否已连接到文件,如果没有,则打开该文件。
我怎样才能得到这种行为(或者至少类似/更好的行为)? 我一直在考虑使文件处理 dataClassA
和 dataClassB
(或基类 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 handlefileA
etc. - When receiving data of type
dataClassA
check whetherfileA
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).