开发者

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

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...!
            sta开发者_高级运维tic 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();
}


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;


Initializing private static members


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;
}


In the header file:

class Nisse
{
    private: 
        static int cnt;

    public: 
...
};

In the cpp file:

int Nisse::cnt = 0;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜