3

I can't get the syntax correct for 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 another functions that would like to use that 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 in the print-function is local to this function, but I would like it to be "private and global in the class".

It feels like I am missing some basic:s c++ syntax here.

/Thanks


Solution:

I was missing the

int Nisse::cnt = 0;

So the 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
  • 20,067
  • 28
  • 92
  • 110

4 Answers4

6

Your commented out code is halfway there. You also need to define it outside the class with a int Nisse::cnt = 0; statement.

EDIT: like this!

class Nisse
{
    private: 
        static int cnt;
    public: 
...     
};
int Nisse::cnt = 0;
Matt K
  • 13,370
  • 2
  • 32
  • 51
3

Initializing private static members

Community
  • 1
  • 1
Ptival
  • 9,167
  • 36
  • 53
2

You can't initialize a static member variable in the class definition.

From your comments, it seems you are a bit confused with C++ syntax, especially since your methods are also defined there like you would 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;
}
Brian Roach
  • 76,169
  • 12
  • 136
  • 161
0

In the header file:

class Nisse
{
    private: 
        static int cnt;

    public: 
...
};

In the cpp file:

int Nisse::cnt = 0;
Benoit Thiery
  • 6,325
  • 4
  • 22
  • 28