I cannot correctly get the syntax with static variables and C ++ classes.
This is a simplified example to show my problem.
I have one function that updates a variable that should be the same for all objects, then I have other functions that would like to use this variable. In this example, I just return it.
#include <QDebug>
class Nisse
{
private:
public:
void print()
{
static int cnt = 0;
cnt ++;
qDebug() << "cnt:" << cnt;
};
int howMany()
{
}
};
int main(int argc, char *argv[])
{
qDebug() << "Hello";
Nisse n1;
n1.print();
Nisse n2;
n2.print();
}
The current local static value in the print function is local to this function, but I would like it to be "private and global in the class".
It seems like I am missing the basic s C ++ syntax.
/Thank
Decision:
I was missing
int Nisse::cnt = 0;
So a working example looks like
#include <QDebug>
class Nisse
{
private:
static int cnt;
public:
void print()
{
cnt ++;
qDebug() << "cnt:" << cnt;
};
int howMany()
{
return cnt;
}
};
int Nisse::cnt = 0;
int main(int argc, char *argv[])
{
qDebug() << "Hello";
Nisse n1;
n1.print();
Nisse n2;
n2.print();
qDebug() << n1.howMany();
}
Johan source
share