【发布时间】:2015-10-25 15:40:16
【问题描述】:
#include<iostream>
using namespace std;
class Test
{
public:
static int Retr(); // Static member function
//~Test(); // Test destructor
Test(); // Default constructor
private:
static int count; // Static member variable
int i;
};
int Test::count = 0; // Initialization
int main()
{
Test obj;
cout << Test::Retr() << endl;
// The result should be 1 but prints two
return 0;
}
Test::Test() : i(1) { Retr(); }
int Test::Retr()
{
return ++count;
}
/*
Test::~Test()
{
count--;
}
*/
我正在练习使用静态成员函数和变量。我有一个静态成员函数,它计算并返回构造了多少个对象。对于这个例子,它应该显示1,但它显示2。我不明白为什么会这样。但是,析构函数减少了每个构造对象的反作用域。不是吗?所以,使用 with 析构函数的结果应该是0。但是,我无法得到预期的结果。谁能解释一下?
编辑了析构函数不起作用怎么办?解决了
#include<iostream>
using namespace std;
class Test
{
public:
static int Retr(); // Static member function
~Test(); // Test destructor
Test(); // Default constructor
private:
static int count; // Static member variable
int i;
};
int Test::count = 0; // Initialization
int main()
{
Test obj[2];
cout << Test::Retr() << endl;
// The result should be 0 because of destructor but prints 2
return 0;
}
Test::Test() : i(1) { ++count; }
int Test::Retr()
{
return count;
}
Test::~Test()
{
--count;
cout << Test::Retr() << endl;
}
【问题讨论】:
标签: c++ destructor static-members