为什么对对象数组不按相反顺序调用析构函数? 析构函数在C++中以对象创建的顺序颠倒,但我不理解为什么它不能被保持在对象数组中。 #include <iostream> using namespace std; class test { int nmbr; static int c; public: test(int j) { cout<<"constructor is called for object no :"<<j<<endl; nmbr=j; }; ~test() { c++; cout<<"destructor is called for object no :"<<c<<endl; }; }; int test::c=0; int main() { test ob[]={test(1),test(2),test(3)}; return 0; }

为什么对对象数组不按相反顺序调用析构函数? 析构函数在C++中以对象创建的顺序颠倒,但我不理解为什么它不能被保持在对象数组中。 #include <iostream> using namespace std; class test { int nmbr; static int c; public: test(int j) { cout<<"constructor is called for object no :"<<j<<endl; nmbr=j; }; ~test() { c++; cout<<"destructor is called for object no :"<<c<<endl; }; }; int test::c=0; int main() { test ob[]={test(1),test(2),test(3)}; return 0; },c++,destructor,C++,Destructor,但是为什么析构函数不按相反的顺序调用呢?它是按相反的顺序调用的。您正在打印变量c。看看我在这个节目中的评论——“我在这里改变了”。您正在打印一个计数变量,您应该在其中打印正在销毁的对象 您可以在此处阅读更多内容: #包括 使用名称空间std; 课堂测试{ int nmbr; 静态int-c; 公众: 测试(int j) { 是的,错误在于您的测试。在调用析构函数时,您正在访问您自己设置的数字。更改析构函数输出以显示类中的实际值,您将自己看到 cout<<"destructor is

但是为什么析构函数不按相反的顺序调用呢?

它是按相反的顺序调用的。您正在打印变量c。看看我在这个节目中的评论——“我在这里改变了”。您正在打印一个计数变量,您应该在其中打印正在销毁的对象

您可以在此处阅读更多内容:

#包括
使用名称空间std;
课堂测试{
int nmbr;
静态int-c;
公众:
测试(int j)
{

是的,错误在于您的测试。在调用析构函数时,您正在访问您自己设置的数字。更改析构函数输出以显示类中的实际值,您将自己看到

cout<<"destructor is called for object no :"<<nmbr<<endl;

cout析构函数的调用顺序与构造函数调用的顺序相反

是您的测试错误地生成和打印了值

尝试此代码,您将看到预期的结果

#include <iostream>

class test {
    int this_instance;
    static int number_of_instances;
public:
    test() : this_instance(number_of_instances++)
    {
        std::cout << "constructor invoked for object :"<< this_instance << '\n';
    };
    ~test()
    {
        std::cout << "destructor invoked for object :" << this_instance << '\n';
    };
};

int test::number_of_instances = 0;

int main()
{
  test first_batch[4];

  return 0;
}
#包括
课堂测试{
int这个例子;
_实例的静态int数_;
公众:
test():此_实例(_实例数++)
{

std::couttry
testob[]={test(97)、test(1043)、test(-12)}
然后看看会发生什么。或者设置test::c=5或除0以外的任意随机数。你会明白,没有,同时写作,也会发生。看不出对那个愚蠢的错误投反对票的任何原因。谢谢,现在我应该删除这篇文章吗?因为这个问题在未来帮助任何人的可能性很小?
cout<<"destructor is called for object no :"<<nmbr<<endl;
#include <iostream>

class test {
    int this_instance;
    static int number_of_instances;
public:
    test() : this_instance(number_of_instances++)
    {
        std::cout << "constructor invoked for object :"<< this_instance << '\n';
    };
    ~test()
    {
        std::cout << "destructor invoked for object :" << this_instance << '\n';
    };
};

int test::number_of_instances = 0;

int main()
{
  test first_batch[4];

  return 0;
}