C++如何在类中获取静态变量?

Joh*_*han 3 c++ static

我无法使用静态变量和c ++类获得正确的语法.

这是一个简单的例子来显示我的问题.

我有一个函数更新一个应该对所有对象都相同的变量,然后我有另一个想要使用该变量的函数.在这个例子中,我只是返回它.

#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();
}
Run Code Online (Sandbox Code Playgroud)

print函数中的当前本地静态是该函数的本地静态,但我希望它是"类中的私有和全局".

感觉我在这里缺少一些基本的:s c ++语法.

/谢谢


方案:

我错过了

int Nisse::cnt = 0;
Run Code Online (Sandbox Code Playgroud)

所以工作示例看起来像

#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();
}
Run Code Online (Sandbox Code Playgroud)

mkb*_*mkb 6

你注释掉的代码就在那里.您还需要使用int Nisse::cnt = 0;语句在类外部定义它.

编辑:像这样!

class Nisse
{
    private: 
        static int cnt;
    public: 
...     
};
int Nisse::cnt = 0;
Run Code Online (Sandbox Code Playgroud)