我正在用 C++ 开发一个具有大量文件 io 操作的程序。我在公共标头中定义了一个静态 ofstream,以便在项目中的任何地方都可以访问它。代码结构如下:所有公共变量都定义在com.h中,test.h和test.cpp是针对一个叫OPClass的类,main.cpp承载主程序
COM.H:
#ifndef __CLCOM__
#define __CLCOM__
#include <sstream>
#include <fstream>
#include <iostream>
using namespace std;
static ofstream out;
static stringstream ss;
#endif
测试.H:
#ifndef __CL__
#define __CL__
#include <iostream>
#include <fstream>
#include "com.h"
using namespace std;
class OPClass
{
  public:
   void run(void);
   void show(ostream &o) const;
};
#endif
测试.CPP:
#include "com.h"
#include "test.h"
void OPClass::run(void)
{
  out << "Here is run()" << endl;
  show(out);
}
void OPClass::show(ostream &o) const
{
  o << "hello!" << endl;
}
主.CPP:
#include "com.h"
#include "test.h"
void runmain(void)
{
  OPClass op;
  out.open("output.txt", ios::out | ios::trunc);
  out << endl << "State changed!" << endl;
  op.run();
  if (out.is_open()) out.close();
}
int main(int argc, char* argv[])
{
  runmain();
  return  0;
}
可以看到,静态的 ofstream 被命名为 out,将在主程序和类中调用。我正在使用 mingw32 并且在编译或运行时没有看到任何问题。但似乎只有 runmain() 中的信息会被写入输出文件。写入类中该文件的任何其他消息永远不会出现在输出文件中。为什么会这样,我如何编写一个通用文件流,以便项目中的任何地方都可以访问它?谢谢。