类里面 new delete 的使用 小栗子(哈哈哈)

本文深入探讨了C++中构造与析构函数的使用,通过具体实例讲解了不同构造函数的作用及调用顺序,同时展示了如何通过析构函数进行资源的清理。

【问题描述】阅读下面的程序,请编写一个不超过五行代码的主函数,使其满足对应的输出要求。

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;

 }


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值