【问题标题】:understanding static member function and variable and destructor理解静态成员函数和变量和析构函数
【发布时间】: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


    【解决方案1】:
    Test::Test() : i(1) { Retr(); }
    

    当你创建了一个对象,它也会调用retr()函数。那就是增加计数;你再一次打电话给retr() 来显示..

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

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

    【讨论】:

      【解决方案2】:

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

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

      所以你的整个程序将只有一个 count 实例(初始化为 0)

      让我们看一下 main 函数中的代码,您正在创建一个 class Test 的对象。因此,构造函数被调用,进而调用static int Retr() 函数。因此count 现在是 1。现在,

      cout << Test::Retr() << endl;
      

      再次调用Retr(),因此它递增count 并返回值。因此返回 2。

      就析构函数而言,它不会在cout 之前调用。只有当obj 超出范围时才会调用它,这只会在主函数完成时发生。

      【讨论】:

        【解决方案3】:

        创建时

            Test obj;
        

        它调用构造函数并递增1

        你又在打电话了

            Test::retr()
        

        它也会增加 1。

        如果你想检查你的类的行为,你可以添加额外的函数

        void testFunction(){
            Test obj[2];
            std::cout << Test::Retr() << std::endl; // count became 3
        }
        int main(){
        
             testFunction();
              // Obj destructed here count became 1
             std::cout << Test::Retr() << std::endl;
             // It will again increment and count will be 2
        }
        

        【讨论】:

        • 你的析构函数会递减 2 次 count 会留下 1,因为你单独调用了 Test Retr() 会增加。
        猜你喜欢
        • 2020-07-15
        • 1970-01-01
        • 2021-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-29
        • 2011-09-07
        相关资源
        最近更新 更多