Bob*_*obS 0 c++ variables static file
我写了一个程序,它都在一个文件中,并且方法在标题中向前声明.该程序最初在一个文件中完美运行.但是当我分离程序时,我不断发现在头文件中声明的类之一的析构函数.
我的标题中有一个静态变量来计算特定类的对象数.每当我构造对象时,我都会增加此变量.然后在我的析构函数中,我从该变量中减去1,检查它是否为0(意味着它是最后一个对象)并执行某些操作.价值似乎有时会消失,我不知道为什么.我的应用程序中有随机调用,但我不明白为什么会影响我上面描述的内容,谢谢.任何帮助或见解表示赞赏!
[更新]:有一个基类,其中包含析构函数..它在头文件中实现,然后我有两个派生类,它们在构造函数中递增静态var ..所以我该怎么办?
我想要做的是以下内容:在我的标题中我有这个:
class A {
public:
virtual ~A() {
count --;
if (count == 0) { /* this is the last one, do something */ }
}
class B : public A {
public:
B();
}
Run Code Online (Sandbox Code Playgroud)
然后在Class BI中有
B::B() {
count++;
}
Run Code Online (Sandbox Code Playgroud)
我在哪里可以定义计数,所以我不会产生误导性的计数?谢谢.
您必须在A(所有这些)中定义构造函数以增加计数.
注意除非你定义它们,否则编译器会自动生成以下四种方法:
以下代码会覆盖编译器默认值,以便您获得准确的计数.
class A
{
static int count;
public:
A() // Default constructor.
{
++count;
}
A(A const& copy) // Copy constructor/
{ // Note If you do not define it the compiler
++count; // will automatically do it for you
}
virtual ~A()
{
--count;
if (count == 0)
{ // PLOP
}
}
// A& operator=(A const& copy)
// do not need to override this as object has
// already been created and accounted for.
};
Run Code Online (Sandbox Code Playgroud)
////在源文件中:
int A::count = 0;
Run Code Online (Sandbox Code Playgroud)