分析构造函数和析构函数调用次序
发布网友
发布时间:2022-05-25 14:53
我来回答
共2个回答
热心网友
时间:2023-11-06 00:08
好无聊的问题,自己随便写点测试代码也有结果了。
原则并不复杂,构造类时,先按继承的顺序构造各父类,完成后,再按成员定义的顺序构造各成员。析构是反序。
热心网友
时间:2023-11-06 00:09
(1)
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout <<"constructing A"<<endl;
}
~A()
{
cout <<"Destructing A"<<endl;
}
};
class C
{
public:
C()
{
cout <<"constructing C"<<endl;
}
~C()
{
cout <<"Destructing C"<<endl;
}
};
class B:public A
{
public:
C c;
B()
{
cout <<"constructing B"<<endl;
}
~B()
{
cout <<"Destructing B"<<endl;
}
};
class D: public B
{
public:
D(){
cout <<"constructing D"<<endl;
}
~D(){
cout <<"Destructing D"<<endl;
}
};
int main()
{
D d;
return 0;
}
输出:
constructing A
constructing C
constructing B
constructing D
Destructing D
Destructing B
Destructing C
Destructing A
(2)
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout <<"constructing A"<<endl;
}
~A()
{
cout <<"Destructing A"<<endl;
}
};
class C:public A
{
public:
C()
{
cout <<"constructing C"<<endl;
}
~C()
{
cout <<"Destructing C"<<endl;
}
};
class B:public A
{
public:
C c;
B()
{
cout <<"constructing B"<<endl;
}
~B()
{
cout <<"Destructing B"<<endl;
}
};
class D: public B
{
public:
D(){
cout <<"constructing D"<<endl;
}
~D(){
cout <<"Destructing D"<<endl;
}
};
输出:
constructing A
constructing A
constructing C
constructing B
constructing D
Destructing D
Destructing B
Destructing C
Destructing A
Destructing A
(3)
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout <<"constructing A"<<endl;
}
~A()
{
cout <<"Destructing A"<<endl;
}
};
class C:virtual public A
{
public:
C()
{
cout <<"constructing C"<<endl;
}
~C()
{
cout <<"Destructing C"<<endl;
}
};
class B:virtual public A
{
public:
C c;
B()
{
cout <<"constructing B"<<endl;
}
~B()
{
cout <<"Destructing B"<<endl;
}
};
class D: public B
{
public:
D(){
cout <<"constructing D"<<endl;
}
~D(){
cout <<"Destructing D"<<endl;
}
};
输出:
constructing A
constructing A
constructing C
constructing B
constructing D
Destructing D
Destructing B
Destructing C
Destructing A
Destructing A