我测试该类的主要方法是"表达式必须具有类类型"当我尝试将枚举传递给函数调用时,我得到"类型不允许"。
#include <iostream>
#include <string>
using std::string;
using std::cout;
class Logger
{
public:
enum LogLevel { ALL, INFO, WARNING, ERROR, NEEDED };
private:
LogLevel Errorlevel = ALL;
string LogLevelNames[5] = { "ALL","INFO","WARNING", "ERROR", "NEEDED" };
public:
Logger(LogLevel level)
{
Errorlevel = level;
if (Errorlevel <= INFO)
{
cout << "[" << LogLevelNames[Errorlevel] << "]: " << "LOGGER set to: " << LogLevelNames[Errorlevel] << std::endl;
}
}
~Logger()
{
if (Errorlevel <= WARNING)
{
cout << "[" << LogLevelNames[Errorlevel] << "]:" << " LOGGER destroyed" << std::endl;
}
}
void log(LogLevel level, string message)
{
if (Errorlevel <= level)
{
cout << "[" << LogLevelNames[level] << "]: " << message << std::endl;
}
}
};
int main()
{
Logger logger(Logger::LogLevel WARNING); // no error
logger.log(Logger::LogLevel ERROR, "test ERROR"); //errors
logger.log(Logger::LogLevel INFO, "test INFO"); //errors
system("PAUSE");
}
我很确定这是由于我自己的经验不足造成的,但我不确定如何改进此代码。
答案 0 :(得分:4)
您在初始化Logger
时遗漏了一些范围,导致编译器无法解析您对log()
的调用。像这样修复它。
int main()
{
Logger logger(Logger::WARNING);
logger.log(Logger::ERROR, "test ERROR");
logger.log(Logger::INFO, "test INFO");
return 0;
}