나는 많은 파일 io 조작으로 C++로 프로그램을 개발 중입니다. 공통 헤더에 static ofstream을 정의하여 프로젝트의 모든 곳에서 액세스 할 수 있도록했습니다. 코드의 구조는 다음과 같습니다. 모든 공통 변수는 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 : 당신이 볼 수 있듯이, 정적 ofstream가 아웃로 명명 된 메인 프로그램 및 클래스에서 호출됩니다
#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;
}
. mingw32를 사용하고 컴파일이나 실행 중 문제가 발생하지 않았습니다. 하지만 runmain()의 정보 만 출력 파일에 기록됩니다. 클래스의 해당 파일에 기록 된 다른 메시지는 출력 파일에 나타나지 않습니다. 그 이유는 무엇이며 프로젝트의 어디에서나 액세스 할 수 있도록 공통 파일 스트림을 어떻게 작성할 수 있습니까? 감사.
감사합니다. 그것은 작동합니다. 나는 단지 하나의 질문을 가지고 있는데 왜 헤더에 "using"문을 써서는 안 되는가? 어쨌든 구현 (즉, cpp)에 대신 넣을 수 있습니까? 덕분에 – user1285419
환영합니다. 'using'은 구현 파일에서는 괜찮지 만 헤더에서 나쁜 습관으로 간주됩니다 ... 왜 그런지에 대한 Q & A가 있습니다 : http://stackoverflow.com/questions/2232496/is-it-wrong-to-use- c-using-a-header-file – HostileFork