在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;
}
Run Code Online (Sandbox Code Playgroud)
上述程序输出
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
Run Code Online (Sandbox Code Playgroud)
但为什么析构函数不会以相反的顺序调用?
它以相反的顺序调用.你正在打印变量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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
406 次 |
| 最近记录: |