C/C++

Simplified Logger Class

by MoA posted Jul 28, 2013
?

단축키

Prev이전 문서

Next다음 문서

ESC닫기

크게 작게 위로 아래로 댓글로 가기 인쇄
#include <iostream>
#include <fstream>

using namespace std;

class Logger
{
 public:
   Logger(const char* filename = "program.log")
     {
       logfile = new fstream(filename, fstream::out);
     }
   ~Logger()
     {
       logfile->close();
       delete logfile;
     }

   Logger& operator<<(const char* msg)
     {
       *logfile << msg;
       return *this;
     }
   Logger& operator<<(const int val)
     {
       *logfile << val;
       return *this;
     }
 private:
   fstream* logfile;
};

class MyClass
{
 public:
   MyClass(const int n)
     {
       data = n;
     }

   ~MyClass()
     {
     }

   friend ostream& operator<<(ostream& o, const MyClass& v)
     {
       return o << "MyClass data = " << v.data << "n";
     }

 private:
   int data;
};

int main()
{
   Logger mainlog;
   MyClass a(10);

   // These work fine
   cout << a;
   mainlog << "Bla " << 200 << "n";

   // This doesn't work
   //mainlog << a;

   return 0;
}