C++:ENUM枚举/日志优化

#include <iostream>

//ENUM 枚举:命名值的方法,是一个整数
//eg:处理三个数
enum Example:unsigned char//默认32位整型,可以这样更改,减少内存使用 必须是整型
{
    A,B=6,C//里面的分组默认代表的是整数,从0开始,所以A代表0...,C代表7
    
};
int a=0;
int b=1;
int c=2;

int main()
{
    Example value=B;//只能赋值枚举中给出的分组
    if (value==2)
    {
        //Do something here
    }
    std::cin.get();
}

理解枚举,成为枚举,超越枚举

原代码


#include <iostream>

class Log
{
public:
    const int LogLevelError=0;
    const int LogLevelWarning=1;
    const int LogLevelInfo=2;
private:
    int m_LogLevel=LogLevelInfo;
    
public:
    void SetLevel(int level)
    {
        m_LogLevel=level;
    }
    
    //const char*字符串的意思
    void Error(const char* message)
    {
        if(m_LogLevel>=LogLevelError)
        std::cout<<"[Error]"<<message<<std::endl;
    }
    void warn(const char* message)
    {
        if(m_LogLevel>=LogLevelWarning)
        std::cout<<"[WARRNING]"<<message<<std::endl;
    }
    
    void Info(const char* message)
    {
        if(m_LogLevel>=LogLevelInfo)
        std::cout<<"[Info]"<<message<<std::endl;
    }
   
};


int main()
{
    Log log;
    //这个方法设置是警告信息的等级 这里设置的是较为重要的警告才打印
    log.SetLevel(log.LogLevelWarning);//warn=1,所以会打印0和1,如果没有,则默认为2,会全部打印
    log.warn("清宵");
    log.Error("清宵");
    
    log.Info("清宵");
    std::cin.get();
}

优化后:

#include <iostream>

class Log
{
public:
    enum Level
    {
        Error,Warning,Info
    };
    //用枚举优化
//    const int LogLevelWarning=1;
//    const int LogLevelInfo=2;
private:
    Level m_LogLevel=Info;
    
public:
    void SetLevel(Level level)
    {
        m_LogLevel=level;
    }
    
    //const char*字符串的意思
    void error(const char* message)
    {
        if(m_LogLevel>=Error)
        std::cout<<"[Error]"<<message<<std::endl;
    }
    void warn(const char* message)
    {
        if(m_LogLevel>=Warning)
        std::cout<<"[WARRNING]"<<message<<std::endl;
    }
    
    void info(const char* message)
    {
        if(m_LogLevel>=Info)
        std::cout<<"[Info]"<<message<<std::endl;
    }
   
};


int main()
{
    Log log;
    //这个方法设置是警告信息的等级 这里设置的是较为重要的警告才打印
    log.SetLevel(Log::Warning);//warn=1,所以会打印0和1,如果没有,则默认为2,会全部打印
    log.warn("清宵");
    log.error("清宵");
    
    log.info("清宵");
    std::cin.get();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值