gpt4 book ai didi

c++ - 为什么不以相反的顺序为对象数组调用析构函数?

转载 作者:太空宇宙 更新时间:2023-11-04 14:53:54 27 4
gpt4 key购买 nike

在 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;
}

以上程序输出

constructor is called for object no :1
constructor is called for object no :2
constructor is called for object no :3
destructor is called for object no :1
destructor is called for object no :2
destructor is called for object no :3

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

最佳答案

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

您可以在这里阅读更多内容: https://isocpp.org/wiki/faq/dtors#order-dtors-for-arrays

#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++;
// I changed here
cout<<"destructor is called for object no :"<<nmbr<<endl;
};
};

int test::c=0;

int main()
{
test ob[]={test(1),test(2),test(3)};
return 0;
}

关于c++ - 为什么不以相反的顺序为对象数组调用析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31246000/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com