Using a static member in a class
Hello,
This is just about C++ and it's very simple.
I'm using QtCreator and MingW .
I define a new console project with the usual main.cpp and a class called myclass. The header is as follows:
Quote:
class MyClass
{
public:
MyClass();
static int getInstanceCount(){return _instanceCount;}
private:
static int _instanceCount;
};
The code is as follows
Quote:
#include "myclass.h"
MyClass::MyClass()
{
_instanceCount++;
}
The code of main is as follows:
Quote:
#include <QtCore/QCoreApplication>
#include <iostream>
using namespace std;
#include "myclass.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyClass foo;
cout<<MyClass::getInstanceCount();
return a.exec();
}
The trouble is that this fails at link time with the repeated message that there is an
undefined reference to MyClass::_instanceCount
What have I done wrong and what can I do to fix it?
Thankyou.
Re: Using a static member in a class
your static member has been declared, but not initialized.
Put this in your .cpp file:
Code:
int MyClass::_instanceCount = 0;
Or change the declaration in the .h file:
Code:
static int _instanceCount = 0;
BTW, this is not related to Qt in any way
Re: Using a static member in a class
I realise that this is not related to Qt in any way. It was just not obvious to find a thread to ask about it and it was pretty easy to answer.
Thank you.
Re: Using a static member in a class
So a better forum would be General programming, rather than Qt programming, which clearly states "For general, non-Qt programming issues."
Re: Using a static member in a class