【发布时间】: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:
是的,忘记类定义后的分号。我不习惯这样做。
【问题讨论】:
-
你忘了用
;终止你的类定义