【问题描述】阅读下面的程序,请编写一个不超过五行代码的主函数,使其满足对应的输出要求。
class CBase1{
int x ;
public:
CBase1( ) { x=0 ; cout<<"GZ CBase1()!"<<endl;}
CBase1(int a) { x=1;cout<<"GZ CBase1(int)!"<<endl;}
~CBase1( ) { cout<<"XG ~CBase1()!"<<endl;}
};
class CBase2{
int y;
public:
CBase2( ) { y=0 ;cout<<"GZ CBase2()!"<<endl;}
CBase2(int a) { y=a ;cout<<"GZ CBase2(int)!"<<endl;}
~CBase2() { cout<<"XG ~CBase2()!"<<endl;}
};
class A{
int x;
public:
A () {x=0; cout<<"GZ A()!"<<endl;}
A(int a) { x=a; cout<<"GZ A(int)!"<<endl;}
~A() { cout<<"XG ~A()!"<<endl;}
};
class CDerived:public CBase1, virtual public CBase2{
A a;
public:
CDerived() { cout<<"GZ CDerived()!"<<endl;}
CDerived(int x,int y ,int z):a(x),CBase1(y),CBase2(z)
{ cout<<"GZ CDerived(int,int)!"<<endl;}
~CDerived() { cout<<"XG ~CDerived()!"<<endl;}
};
int main(){ //请补充,不允许超过五行代码 }
【样例输出】
GZ CBase2()!
GZ CBase1()!
GZ A()!
GZ CDerived()!
GZ CBase2(int)!
GZ CBase1(int)!
GZ A(int)!
GZ CDerived(int,int)!
XG ~CDerived()!
XG ~A()!
XG ~CBase1()!
XG ~CBase2()!
main() OVER!
XG ~CDerived()!
XG ~A()!
XG ~CBase1()!
XG ~CBase2()!
#include <iostream>
using namespace std;
class CBase1{
int x ;
public:
CBase1( ) { x=0 ; cout<<"GZ CBase1()!"<<endl;}
CBase1(int a) { x=1;cout<<"GZ CBase1(int)!"<<endl;}
~CBase1( ) { cout<<"XG ~CBase1()!"<<endl;}
};
class CBase2{
int y;
public:
CBase2( ) { y=0 ;cout<<"GZ CBase2()!"<<endl;}
CBase2(int a) { y=a ;cout<<"GZ CBase2(int)!"<<endl;}
~CBase2() { cout<<"XG ~CBase2()!"<<endl;}
};
class A{
int x;
public:
A () {x=0; cout<<"GZ A()!"<<endl;}
A(int a) { x=a; cout<<"GZ A(int)!"<<endl;}
~A() { cout<<"XG ~A()!"<<endl;}
};
class CDerived:public CBase1, virtual public CBase2{
A a;
public:
CDerived() { cout<<"GZ CDerived()!"<<endl;}
CDerived(int x,int y ,int z):a(x),CBase1(y),CBase2(z)
{ cout<<"GZ CDerived(int,int)!"<<endl;}
~CDerived() { cout<<"XG ~CDerived()!"<<endl;}
};
int main()
{ int x,y,z;
CDerived * cderived1=new CDerived();
CDerived cderived2(x,y,z);
delete cderived1;//这一步释放类的成员 就相当于调用析构函数 这里用代码写出来后就会先执行析构函数
/*CBase2 base2(x);
CBase1 base1(x);
A a(x);*/如果主函数没有要求 限制代码行数 那这里也可以这样写
cout<<"main() OVER!"<<endl;//执行完不带参数的cderived1的析构任务之后 就输出“main() OVER!”
//最后一步,系统自动调用cderived2(x,y,z)的析构函数
return 0;
}
本文深入探讨了C++中构造与析构函数的使用,通过具体实例讲解了不同构造函数的作用及调用顺序,同时展示了如何通过析构函数进行资源的清理。

被折叠的 条评论
为什么被折叠?



