#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();
}