我在C開發程序++有很多文件IO操作。我在一個共同的頭文件中定義了一個靜態的流,以便在項目中的任何地方都可以訪問它。碼的結構如下面的列表:所有公共變量在com.h,test.h和TEST.CPP定義是一個名爲的opclass類,main.cpp中攜帶主程序爲什麼靜態的ofstream不起作用
COM.H:
#ifndef __CLCOM__
#define __CLCOM__
#include <sstream>
#include <fstream>
#include <iostream>
using namespace std;
static ofstream out;
static stringstream ss;
#endif
TEST.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
TEST.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;
}
main.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被命名爲出,將在主程序和在類中調用。我使用的是mingw32,在編譯或運行時沒有看到任何問題。但似乎只有runmain()中的信息將被寫入輸出文件。寫入該文件的任何其他消息都不會出現在輸出文件中。爲什麼這麼做,我該如何編寫一個公共文件流,以便項目中的任何地方都可以訪問它?謝謝。
非常感謝。有用。我只有一個問題,爲什麼我們不應該在頭文件中使用「使用」語句?無論如何,我可以把它放在執行(即cpp)嗎?謝謝 – user1285419 2012-04-21 06:08:06
歡迎。在實現文件中使用''是好的,但是在頭文件中被認爲是一個不好的做法......這是關於爲什麼是這種情況的Q&A:http://stackoverflow.com/questions/2232496/is-it-wrong-to-use- C-使用關鍵字 - 在-A-頭文件 – HostileFork 2012-04-21 06:10:41