简体   繁体   中英

C++ class static member initialization

I am using Qt 5.2.1 on Ubuntu Linux 12.04 LTS. Here is the definition of my class (.h):

class RtNamedInstance
{
    // [... other code here ...]

public:
    static int _nextInstanceNumber;
    static QMutex _syncObj;
};

and here my implementation (.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

What am I missing?

As suggested by @JoachimPileborg, I was simply forgetting to type the QMutexLocker variable name... and this confused somehow the compiler...

The correct code is (.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 ...]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM