这是.h:
class Logger
{
private:
static int mTresholdSeverity;
public:
static __declspec(dllexport) void log(const char* message);
static __declspec(dllexport) void logFormat(const char* format, ...);
static __declspec(dllexport) int getTresholdSeverity() { return mTresholdSeverity; }
static __declspec(dllexport) void setTresholdSeverity(int tresholdSeverity) { mTresholdSeverity = tresholdSeverity; }
};
和.cpp:
#include "Logger.h"
#include <cstdarg>
int Logger::mTresholdSeverity = 200;
void Logger::log(const char* message)
{
//...
}
void Logger::logFormat(const char* format, ...)
{
//...
}
我收到此错误:
错误 LNK2001:未解析的外部符号“私有:静态 int TransformationViewer_Utility_Logging::Logger::mTresholdSeverity”(?mTresholdSeverity@Logger@TransformationViewer_Utility_Logging@@0HA) ...
显然,mTresholdSeverity 已初始化。如果我注释掉 getTresholdSeverity() 和 setTresholdSeverity() 或者如果我将它们的定义移到 .cpp 文件中,则会删除该错误。
当头文件中定义的静态方法(getTresholdSeverity() 或 setTresholdSeverity())使用静态变量(mTresholdSeverity)时,为什么会出现链接错误?