我无法相信听起来如此简单的事情会如此困难。
class OutputHandler {
private:
static std::string const errorPrefixes[] = {"INFO", "WARNING", "ERROR", "CRASH"};
};
我该如何正确地做到这一点?从各种文档中,我了解到我无法初始化静态成员对象,无论它们是恒定的。
Write the initialization outside the class, together with the definition:
class OutputHandler
{
private:
static std::string const errorPrefixes[];
};
std::string const OutputHandler::errorPrefixes[] = {"INFO", "WARNING", "ERROR", "CRASH"};
(The definition is of course subject to the one-definition-rule and must only appear in one single translation unit, e.g. OutputHandler.cpp
.)
您必须static
在源文件中初始化您的成员以满足one-definition-rule:
// in .h
class OutputHandler {
private:
static std::string const errorPrefixes[]; // declaration
};
// in .cpp
// definition
std::string const OutputHandler::errorPrefixes[] = {"INFO", "WARNING", "ERROR", "CRASH"};