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

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

Severity	Code	Description	Project	File	Line	Suppression State
Error	LNK2001	unresolved external symbol "private: static class QColor * Helper::lineColor" (?lineColor@Helper@@0PEAVQColor@@EA)	QtOpenCVProjE2	E:\VSProj\QtOpenCVProjE2\QtOpenCVProjE2\Helper.obj	1	

 如下图所示:

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

在参考文章《error LNK2001:未解析的外部符号“private:static class(error LNK2001: unresolved external symbol "private: static class)》(https://www.it1352.com/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)》(https://www.it1352.com/476238.html)】

 

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

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

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

 

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值