C++类静态成员变量导致报错error LNK2001: unresolved external symbol “private: static class

转自:https://blog.csdn.net/Owen_Suen/article/details/104762593

今天在为Qt+OpenCV项目添加工具类Class  Helper的时候,静态变量和静态函数总会导致报错

 
  1. Severity Code Description Project File Line Suppression State

  2. Error LNK2001 unresolved external symbol "private: static class QColor * Helper::lineColor" (?lineColor@Helper@@0PEAVQColor@@EA) QtOpenCVProjE2 E:\VSProj\QtOpenCVProjE2\QtOpenCVProjE2\Helper.obj 1

 如下图所示:

当仅有静态变量,而不对静态变量做读写时候并不会报错;但是当改动其值时候,就会报错LNK2001

C++类静态成员变量导致报错error LNK2001: unresolved external symbol “private: static class_第1张图片

在参考文章《error LNK2001:未解析的外部符号“private:static class(error LNK2001: unresolved external symbol "private: static class)》(https://www.it1352.com/476238.html)之后,找到了原因

需要在源代码文件.cpp文件中添加一句静态非常量成员变量的定义

QColor* Helper::lineColor;

如图所示:

C++类静态成员变量导致报错error LNK2001: unresolved external symbol “private: static class_第2张图片



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)》(https://www.it1352.com/476238.html)】

 

静态但非常量成员变量应该在类定义之外,该类所属的命名空间之内,进行定义。

一般惯例将其定义在翻译单元(即.cpp文件)中,引起被视为实现细节。

只有静态常量整型变量才能在同一处声明与定义(即在类内定义)。

 

你可能感兴趣的:(c++,基础,静态,成员变量,error,LNK2001,static,already,defined)