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

mow*_*ker 11 c++ static class

我想有一个静态成员变量跟踪已经创建的对象的数量.像这样:

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

        }
}
Run Code Online (Sandbox Code Playgroud)

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

test::count = 0;
Run Code Online (Sandbox Code Playgroud)

哪个会很棒,但我想要算是私人的.

编辑: 哦,小伙子,我才意识到我需要这样做:

int test::count = 0;
Run Code Online (Sandbox Code Playgroud)

我曾经看到过一些事情test::count = 0,所以我认为你不必再宣告类型了.

我想知道是否有办法在课堂上这样做.

EDIT2:

我在用什么:

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

        }
}
int test::count=0;
Run Code Online (Sandbox Code Playgroud)

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

EDIT3:

是的,在课程定义后忘了分号.我不习惯这样做.

Set*_*gie 14

static int count;
Run Code Online (Sandbox Code Playgroud)

在类定义的标题中,和

int test::count = 0;
Run Code Online (Sandbox Code Playgroud)

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

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


小智 5

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

 class test
 {
    private:
    static int & getCount ()
    {
       static int theCount = 0;
       return theCount;
    }
    public:
    int totalCount ()
    {
       return getCount ();
    }

    test()
    {      
       getCount () ++;
    }
 };
Run Code Online (Sandbox Code Playgroud)

一般来说,使用此技术可以解决有关声明中静态成员初始化的 C++ 限制。