将信息写入文件,可作为简单日志类
#include <iostream>
#include <fstream>
using namespace std;
class LOG
{
public:
LOG(void);
~LOG(void);
public:
bool Init(const char*file, const char*mode);
//第一个const表示返回的对象不可被外部修改
//随后一个const表示将函数设为const函数,使其可以被const对象调用
const LOG& operator <<(const char*value)const;//返回const对象实现函数重复调用
const LOG& operator <<(const int value)const;
const LOG& operator <<(const LOG&(*op)(const LOG&))const;
void flush()const;
private:
FILE*pfile;
};
LOG::LOG()
{
pfile = nullptr;
}
LOG::~LOG()
{
if (pfile)
fclose(pfile);
}
bool LOG::Init(const char*file, const char*mode)
{
pfile = fopen(file, mode);
if (pfile)
return true;
else
return false;
}
const LOG& LOG::operator <<(const char*value)const
{
fprintf(pfile, value);
return *this;
}
const LOG& LOG::operator <<(const int value)const
{
fprintf(pfile, "%d", value);
return *this;
}
const LOG& LOG::operator <<(const LOG&(*op)(const LOG&))const
{
return (*op)(*this);//传递函数指针调用函数
}
void LOG::flush()const
{
fprintf(pfile, "\n");
fflush(pfile);
return;
}
namespace MYLOG
{
//实现endl
template<class T>
inline const T&endl(const T&op)
{
op.flush();//调用flush方法
return op;
}
}
//endl实际上是一个函数函数指针,在<<流重载操作中调用这个函数指针实现 换行与 flush方法
int main()
{
LOG log;
log.Init("../test.txt", "a+");
log << "helloworld!" << 1234 << MYLOG::endl << 12344 << MYLOG::endl;
cin.get();
return 0;
}
关于endl:https://www.cnblogs.com/ldeng/archive/2012/09/02/2667942.html