처음에 나는 ostream
에서 클래스를 파생한다고 말하는 많은 게시물을 보았습니다.하지만 'ostream` 자체가 스트림에 버퍼를 제공해야하기 때문에 이해할 만합니다.왜 << 연산자가 ofstream의 파생 클래스에서 작동하지 않습니까?
fstream
또는 ofstream
에서 파생되는 것은 어떻게됩니까? 이 기본 클래스는 버퍼 설정을 가지고 있고 그것들로부터 파생되어 단지 fstream
을 인스턴스화하고 캡슐화하기 때문에 이것이 간단해야한다고 생각합니다.
class lfstream : public std::ofstream
{
public:
lfstream();
~lfstream();
void log(const std::string &text);
protected:
std::ofstream logfile;
char logfname[32];
};
extern lfstream ls;
해당 CPP 파일이 main() 함수에서 이제
lfstream ls; // global object of log file so I can write to it
lfstream::lfstream() : logfname("Mylog.txt")
{
logfile.open(logfname, std::ios_base::out | std::ios_base::app);
}
lfstream::~lfstream()
{
}
void lfstream::log(const std::string &text)
{
logfile << text;
}
입니다 만드는 오전
int main(int argc, char * argv)
{
// this is for camparison, << operator works on ofstream
std::ofstream stockstream("ostream_test.txt");
stockstream << "<< test ostream" << std::endl; // works
// But << doesn't work on my derived class which is also a stream
ls << "<< test ls stream"; // why this doesn't go into the file?
ls.log("This works"); // but this does
}
내 첫 번째 질문은 위와 같은 ostream
에서 파생되었습니다. 알았습니까? 둘째, <<
이 파생 클래스에서 작동하지 않는 이유는 무엇입니까?
업데이트 그래서 내 구현은 틀렸다. 나는 멤버 변수 ofstream
개체가 이제 생성자는 다음과 같이된다 eleminated :
lfstream::lfstream() : logfname("debug_log.txt"), std::ofstream(logfname)
{
}
하지만 어떻게 내가 지금 로그() 함수를 구현합니까?
업데이트 2
내 로그는 실제로 따라 형식을에서 인쇄 더 많은 데이터를 않습니다. 이것은 단지 ofstream
void lfstream::log(const std::string &text)
{
const time_t ctt = time(0);
int threadID = GetCurrentThreadId();
logfile << std::setw(40) << std::left << text << " thread id = " << threadID << "\t" << asctime(localtime(&ctt)); // << std::endl;
}
이 내가 ls.log(...)
를 호출 할 수 있습니다 의미는 형식화하는 작업을 수행 내가 인스턴스화하지하고있는 이유입니다.
다른 것들과 별개로, 당신은 ofstream_and_에서 보호 된 ofstream 멤버가 있습니다. –
그리고 당신의 로그 함수는 (열린) 멤버에게 쓰고 연산자 <<는 열리지 않은베이스에 쓰게됩니다 –
@NeilButterworth 좋은 지적입니다! 그게 옳은 것 같지 않습니다. 제 코드를 돌아 보겠습니다. – zar