#include<iostream> using namespace std; class Log { public: const int Erroring = 0; //错误 const int Warning = 1; //警告 const int Info = 2; private: //标记私有 int m_loglevel; public: //标记公开 void SetLevel(int level) { m_loglevel = level; } void Error(const char* a) { if (m_loglevel >= Erroring){ std::cout << "[Error]: " << a << std::endl; } } void Warn(const char* a) { if (m_loglevel >= Warning) { std::cout << "[Warning]: " << a << std::endl; } } void Information(const char* a) { if (m_loglevel >= Info) { std::cout << "[Information]: " << a << std::endl; } } Log() = default; }; int main() { Log log; log.SetLevel(log.Warning);//打印的程度 log.Warn("Hello 1"); log.Error("Hello 2"); log.Information("Hello 3"); std::cin.get(); }
时间: 2024-04-10 20:34:12 浏览: 28
这段代码定义了一个名为 Log 的类,用于记录不同级别的日志消息。代码中的主要部分如下:
```cpp
class Log {
public:
const int Erroring = 0; //错误
const int Warning = 1; //警告
const int Info = 2;
private:
int m_loglevel; //日志级别
public:
void SetLevel(int level) {
m_loglevel = level;
}
void Error(const char* a) {
if (m_loglevel >= Erroring) {
std::cout << "[Error]: " << a << std::endl;
}
}
void Warn(const char* a) {
if (m_loglevel >= Warning) {
std::cout << "[Warning]: " << a << std::endl;
}
}
void Information(const char* a) {
if (m_loglevel >= Info) {
std::cout << "[Information]: " << a << std::endl;
}
}
Log() = default;
};
```
在 `main()` 函数中,我们创建了一个名为 `log` 的 `Log` 类对象,然后通过调用 `SetLevel()` 方法来设置日志级别。接下来,我们使用 `Warn()`、`Error()` 和 `Information()` 方法分别输出不同级别的日志消息。
运行这段代码将输出以下内容:
```
[Warning]: Hello 1
[Error]: Hello 2
```
由于日志级别设置为 `Warning`,所以只有警告级别和更高级别的日志消息被打印出来。
希望这能帮助到你!如果你有任何其他问题,请随时提问。