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

标签 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();
}

打印函数中的当前局部静态是该函数的局部变量, 但我希望它是“类里面的私有(private)和全局”。

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

/谢谢


解决方案:

我错过了

int Nisse::cnt = 0;

所以工作示例看起来像

#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();
}

最佳答案

您注释掉的代码已完成一半。您还需要使用 int Nisse::cnt = 0; 语句在类外定义它。

编辑:像这样!

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

关于C++如何获取类中的静态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5341926/

相关文章:

c++ - 使用 CMake 构建 {fmt} 时出现问题

c++ - 函数模板参数推导适用于 gcc,但不适用于 msvc 和 clang

c - 覆盖函数指针后面的c静态函数

php - 无法在 Laravel 中调用自定义函数

java - main 方法调用非静态方法

static - 如何从 Mongoose 中的实例方法访问静态方法?

c++ - 构造函数(线程)后类成员更改地址

c++ - 计算所有的子矩阵

c++ - 制作不存储 value_type 的 InputIterator

java - 对类加载时未知的常量使用 final 和 static