[英]C++ class static member initialization
I am using Qt 5.2.1 on Ubuntu Linux 12.04 LTS. 我在Ubuntu Linux 12.04 LTS上使用Qt 5.2.1。 Here is the definition of my class (.h): 这是我的班级(.h)的定义:
class RtNamedInstance
{
// [... other code here ...]
public:
static int _nextInstanceNumber;
static QMutex _syncObj;
};
and here my implementation (.cpp): 这是我的实现(.cpp):
#include "rtnamedinstance.h"
// Initialize static members
int RtNamedInstance::_nextInstanceNumber = 0;
QMutex RtNamedInstance::_syncObj(QMutex::Recursive);
RtNamedInstance::RtNamedInstance(QString instanceName)
{
QMutexLocker(&_syncObj); // (*)
// [... other code here ...]
}
The compiler exits with the following error on line marked (*)
: 编译器退出,并在标记为(*)
行上出现以下错误:
rtnamedinstance.cpp: In constructor 'RtNamedInstance::RtNamedInstance(QString)': rtnamedinstance.cpp:9:27: error: '_syncObj' declared as reference but not initialized rtnamedinstance.cpp:在构造函数'RtNamedInstance :: RtNamedInstance(QString)'中:rtnamedinstance.cpp:9:27:错误:'_syncObj'声明为引用但未初始化
What am I missing? 我想念什么?
As suggested by @JoachimPileborg, I was simply forgetting to type the QMutexLocker variable name... and this confused somehow the compiler... 正如@JoachimPileborg所建议的那样,我只是忘记键入QMutexLocker变量名...而这在某种程度上使编译器感到困惑...
The correct code is (.cpp): 正确的代码是(.cpp):
#include "rtnamedinstance.h"
// Initialize static members
int RtNamedInstance::_nextInstanceNumber = 0;
QMutex RtNamedInstance::_syncObj(QMutex::Recursive);
RtNamedInstance::RtNamedInstance(QString instanceName)
{
QMutexLocker locker(&_syncObj);
// [... other code here ...]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.