【问题标题】:Static variable for object count in c++ classes?c++ 类中对象计数的静态变量?
【发布时间】:2011-12-08 12:47:47
【问题描述】:

我希望有一个静态成员变量来跟踪已创建的对象数量。像这样:

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:

是的,忘记类定义后的分号。我不习惯这样做。

【问题讨论】:

  • 你忘了用;终止你的类定义

标签: c++ class static


【解决方案1】:

static int count;

在类定义的标题中,并且

int test::count = 0;

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

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

【讨论】:

  • 现在说:'test' followed by 'int' is illegal (did you forget a ';'?)
  • @Walkerneo 粘贴您编写的代码。请注意,除了删除 = 0 之外,标题应保持与之前相同。
  • 顺便说一句,都在同一个文件里,我没有分开。有问题吗?
  • @Walkerneo 如果它们都在同一个文件中,那么您必须确保您的文件在整个项目中只包含一次。如果它被多次包含,你会得到一个多重定义错误。澄清一下,int test::count = 0 必须在类定义之外。
  • @Walkerneo 而你在课程结束时忘记了;
【解决方案2】:

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

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

    test()
    {      
       getCount () ++;
    }
 };

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-30
      • 1970-01-01
      • 1970-01-01
      • 2020-01-12
      • 1970-01-01
      • 1970-01-01
      • 2014-01-22
      • 2011-08-27
      相关资源
      最近更新 更多