C ++ how to get a static variable in a class?

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: 
        //I would like to put it here:
        //static int cnt;
    public: 
        void print()
        {
            //And not here...!
            static int cnt = 0;
            cnt ++;
            qDebug() << "cnt:" << cnt;
        };

        int howMany()
        {
            //So I can return it here.
            //return cnt;
        }
};

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();
}
+3
source share
4 answers

. int Nisse::cnt = 0;.

: !

class Nisse
{
    private: 
        static int cnt;
    public: 
...     
};
int Nisse::cnt = 0;
+6

+3

You cannot initialize a static member variable in a class definition.

From your comments, it seems that you are a little confused with the C ++ syntax, especially since your methods are also defined there, as in Java.

file name Nisse.h

#include <QDebug>

class Nisse
{
    private: 
        static int cnt;
    public: 
        void print();
        int howMany();

};

file named Nisse.cc

Nisse::cnt = 0;

void Nisse::print()
{
    cnt++;
    qDebug() << "cnt:" << cnt;
}

int Nisse::howMany()
{
    //So I can return it here.
    return cnt;
}
+2
source

In the header file:

class Nisse
{
    private: 
        static int cnt;

    public: 
...
};

In the cpp file:

int Nisse::cnt = 0;
0
source

All Articles