今天在为Qt+OpenCV项目添加工具类Class Helper的时候,静态变量和静态函数总会导致报错
SeverityCodeDescriptionProjectFileLineSuppression StateErrorLNK2001unresolved external symbol "private: static class QColor * Helper::lineColor" (?lineColor@Helper@@0PEAVQColor@@EA)QtOpenCVProjE2E:\VSProj\QtOpenCVProjE2\QtOpenCVProjE2\Helper.obj1
如下图所示:
当仅有静态变量,而不对静态变量做读写时候并不会报错;但是当改动其值时候,就会报错LNK2001
在参考文章《error LNK2001:未解析的外部符号“private:static class(error LNK2001: unresolved external symbol "private: static class)》(/476238.html)之后,找到了原因
需要在源代码文件.cpp文件中添加一句静态非常量成员变量的定义
QColor* Helper::lineColor;
如图所示:
static, but non-const data members should be defined outside of the class definition and inside the namespace enclosing the class. The usual practice is to define it in the translation unit (*.cpp) because it is considered to be an implementation detail. Only static and const integral types can be declared and defined at the same time (inside class definition).
【来自上述参考文章《error LNK2001:未解析的外部符号“private:static class(error LNK2001: unresolved external symbol "private: static class)》(/476238.html)】
静态但非常量成员变量应该在类定义之外,该类所属的命名空间之内,进行定义。
一般惯例将其定义在翻译单元(即.cpp文件)中,引起被视为实现细节。
只有静态常量整型变量才能在同一处声明与定义(即在类内定义)。