2

我无法相信听起来如此简单的事情会如此困难。

class OutputHandler {
private:
    static std::string const errorPrefixes[] = {"INFO", "WARNING", "ERROR", "CRASH"};
};

我该如何正确地做到这一点?从各种文档中,我了解到我无法初始化静态成员对象,无论它们是恒定的。

4

2 回答 2

3

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.)

于 2013-10-06T13:35:50.103 回答
3

您必须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"};
于 2013-10-06T13:37:38.710 回答