C++ 理解静态成员函数、变量和析构函数

C++ 理解静态成员函数、变量和析构函数,c++,destructor,static-members,C++,Destructor,Static Members,当您创建 #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

当您创建

#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;
}
它调用构造函数并递增1

你又打电话来了

    Test obj;
它还增加1

如果要检查类的行为,可以添加其他函数

    Test::retr()
void testFunction(){
试验对象[2];
标准::cout
当您创建了一个对象时,它也会调用
retr()
函数。这会增加计数;您再次调用
retr()
来显示

您的析构函数正在工作。请调用
Test::Retr()
检查销毁后的计数

Test::Test() : i(1) { Retr(); }
Test::~Test()
{
--计数;

首先,您需要了解什么是静态成员函数

类的静态成员与类的对象不关联:它们是具有静态存储持续时间的独立对象,或在命名空间范围中定义的常规函数,在程序中仅定义一次

因此,整个程序将只有一个
count
实例(初始化为0)

让我们看一下主函数中的代码,您正在创建一个
类测试的对象
。因此会调用构造函数,它在inturn中调用
static int Retr()
函数。因此
count
现在是1。现在

Test::~Test()
{
    --count;
    cout << Test::Retr() << endl;
}

cout您的析构函数将递减计数2次,并保留1,这是因为您单独调用了Test Retr()。
Test::Test() : i(1) { Retr(); }
Test::~Test()
{
    --count;
    cout << Test::Retr() << endl;
}
cout << Test::Retr() << endl;