2017-09-29 1 views
-2

처음에 나는 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(...)를 호출 할 수 있습니다 의미는 형식화하는 작업을 수행 내가 인스턴스화하지하고있는 이유입니다.

+1

다른 것들과 별개로, 당신은 ofstream_and_에서 보호 된 ofstream 멤버가 있습니다. –

+1

그리고 당신의 로그 함수는 (열린) 멤버에게 쓰고 연산자 <<는 열리지 않은베이스에 쓰게됩니다 –

+0

@NeilButterworth 좋은 지적입니다! 그게 옳은 것 같지 않습니다. 제 코드를 돌아 보겠습니다. – zar

답변

1

나는 답변을 게시하고 있습니다. 동시에 원래의 코드에는 구성과 상속을 동시에 사용 했으므로 결함이있었습니다 (이것을 지적한 주석 덕분에). 두 가지 방법 모두 다른 형태의 솔루션을 제공하므로 먼저 사용할 솔루션을 결정해야합니다.

구성 내 클래스 그래서 난 그냥 그 멤버 변수에 작업을 위임 ofstream에서 파생하지 않았다 std::ofstream logfile;를 선언했다

. 이것은 구성입니다.

상속

내 수업이 std::ofstream에서 파생 된 이후, 나는 같은 멤버 변수를 선언하지 않았다. 제거 된 클래스는 다음과 같이 보입니다. 아이디어는 ofstream을 모방하여 동일한 생성자를 구현하고 기본으로 ofstream 클래스를 인스턴스화합니다 (단 하나의 생성자 만 구현했습니다).

lfstream::lfstream(const std::string& logfilename) : _logfname(logfilename), 
     std::ofstream(logfilename) 
{ 
} 

lfstream::~lfstream() 
{ 
} 

void lfstream::log(const std::string &text) 
{ 
    *this << text; 
} 

이 원래 문제를 내 파생 클래스에 지금 << 작품을 수정한다.

+0

답변으로 문제가 해결되었다고 생각한다면 받아 들일 수 있습니다.) – user463035818

관련 문제