Log.h
/*************************************************************************
> File Name: Log.h
> Author:
> Mail:
> Created Time: 2020年06月15日 星期一 09时55分06秒
************************************************************************/
#ifndef _LOG_H
#define _LOG_H
#include<fstream>
#include<string>
class Log{//在.h文件中只有函数的声明,没有函数的实现({}大括号成为函数的实现)
public:
static void Init(int level = DEBUG);
static void Debug(std::string msg, bool fileOnly = false);
enum{
DEBUG = 1, //后面的值就从2开始递增,enum中存储的是一个个的整型数据,按照递增的顺序,好在可以方便命名
INFO,
MESSAGE,
FATAL
};
static void SetLevel(int level);
static void SetLevel(std::string strLevel);
static int GetLevel();
private:
static std::string logFilename;
static int level;
};
#endif
使用static关键字的好处是,使用了static关键字修饰的成员变量或者成员函数是属于整个类的,所以可以直接通过类名来进行访问。也就是说,不需要通过类的实例化对象的方式进行访问。
Log.cpp
/*************************************************************************
> File Name: Log.cpp
> Author:
> Mail:
> Created Time: 2020年06月15日 星期一 10时02分40秒
************************************************************************/
#include "Log.h"
using namespace std;
int Log::level = Log::DEBUG;//这一行要有,否则编译的时候会报错:找不到引用(相当于为成员变量开辟内存)
void Log::SetLevel(string strLevel){
int tmpLevel = 0;
Log::SetLevel(Log::DEBUG);
Log::SetLevel(tmpLevel);
}
void Log::SetLevel(int level){
Log::level = level;
}
int Log::GetLevel(){//相当于为成员函数开辟内存
return Log::level;
}
LogMain.cpp
/*************************************************************************
> File Name: LogMain.cpp
> Author:
> Mail:
> Created Time: 2020年06月15日 星期一 14时12分33秒
************************************************************************/
#include<iostream>
using namespace std;
#include "Log.h"
int main(){
Log::SetLevel(3);
cout << Log::GetLevel() << endl;
return 0;
}
编译运行(g++ -o LogMain Log.cpp LogMain.cpp )
acat@acat-xx:mycode$ g++ -o LogMain Log.cpp LogMain.cpp
acat@acat-xx:mycode$ ./LogMain
3