c++类中用于对象计数的静态变量

Static variable for object count in c++ classes?

本文关键字:静态 变量 对象 用于 c++      更新时间:2023-10-16

我想有一个静态成员变量来跟踪已经制作的对象的数量。像这样:

class test{
    static int count = 0;
    public:
        test(){
            count++;
        }
}

这不起作用,因为根据vc++, a member with an in-class initializer must be constant。所以我环顾四周,显然你应该这样做:

test::count = 0;

这很好,但是我希望count是私有的。

编辑:

哦,天哪,我刚意识到我需要做:

int test::count = 0;

我看到一些东西只是做test::count = 0,所以我认为你不需要再次声明类型。

我想知道是否有一种方法可以在类中做到这一点。

edit2:

我在用什么:

class test{
    private:
        static int count;
    public:
        int getCount(){
            return count;
        }
        test(){
            count++;
        }
}
int test::count=0;

现在显示:'test' followed by 'int' is illegal (did you forget a ';'?)

edit3:

是的,在类定义之后忘记了一个分号。我不习惯这样做。

Put

static int count;

在类定义的头文件中,和

int test::count = 0;

在.cpp文件。它仍然是私有的(如果你将声明留在类的私有部分的头文件中)。

您需要这样做的原因是因为static int count是一个变量声明,但是您需要在单个源文件中定义,以便链接器知道当您使用名称test::count时您引用的内存位置。

允许在函数中初始化静态变量,因此解决方案可以像这样

 class test
 {
    private:
    static int & getCount ()
    {
       static int theCount = 0;
       return theCount;
    }
    public:
    int totalCount ()
    {
       return getCount ();
    }
    test()
    {      
       getCount () ++;
    }
 };
一般来说,使用这种技术可以绕过c++在声明中关于静态成员初始化的限制。

static类成员必须在命名空间范围内定义(并可能初始化),成员访问规则不适用