c++类中用于对象计数的静态变量
Static variable for object count in c++ classes?
我想有一个静态成员变量来跟踪已经制作的对象的数量。像这样:
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 () ++;
}
};
static
类成员必须在命名空间范围内定义(并可能初始化),成员访问规则不适用
相关文章:
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 模板基类中的静态变量
- 类和静态变量
- 不同作用域中的静态变量和全局变量
- 静态变量声明和定义
- 是否可以依赖函数范围的静态变量来执行程序关闭期间调用的方法?
- 在类中继承静态变量?
- "local scope"中的 C++ 初始化静态变量
- 使用静态变量的递归调用的不同输出
- 复制文件流C++静态变量
- 跨模板化函数编译的静态变量
- C++编译器是否优化了顺序静态变量读取?
- C++,每个循环初始化一个新的静态变量
- (为什么)我们可以在初始化中将非静态类成员分配给静态变量吗?
- 这些语句是否等效(静态变量、常量变量和泛型)
- 程序如何知道静态变量是否需要初始化?
- 类外的静态变量实例化
- 无法解析静态变量
- 函数局部静态变量:从性能角度来看的优点/缺点
- 访问从 CPP 文件到其他头文件的静态变量